在 JavaFx Textfield Focus 属性 中需要有关在聚焦后更改文本的帮助

Need help in JavaFx Textfield Focus property about changing the text after focus out

在 Javafx 文本字段焦点 属性 中需要帮助,如果使用焦点 属性 输入大于 12 的数字,我想更改文本字段中的文本,当我聚焦文本字段时,然后它必须把里面的文字改成12 我使用的代码是

NumberTextField numberTextField = new NumberTextField();
    numberTextField.setLayoutX(280);
    numberTextField.setLayoutY(280);
    //Textfield1 working
   numberTextField.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
       if (newPropertyValue)
        {

        }
        else
        {
            if(numberTextField.getText() == "" && Integer.parseInt(numberTextField.getText()) > 12)
            {

            }
            numberTextField.setText("12");
            System.out.println("Textfield 1 out focus");
        }


    });

而数字文本字段 class 是

    public class NumberTextField extends TextField
{
 @Override
    public void replaceText(int start, int end, String text)
    {
        if (validate(text))
        {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text)
    {
        if (validate(text))
        {
            super.replaceSelection(text);
        }
    }

    private boolean validate(String text)
    {

       return ("".equals(text) || text.matches("[0-9]"));
    }
}

所以它工作正常,它会在我聚焦时更改文本字段的文本,而不是在输入任何文本之后,或者当我输入小于 12 的文本时。

你写错了condition。要编写适当的条件,请学习 Trueth 表 See this

    NumberTextField numberTextField = new NumberTextField();
    numberTextField.setLayoutX(280);
    numberTextField.setLayoutY(280);
    // Textfield1 working
    numberTextField.focusedProperty().addListener((arg0, oldPropertyValue, newPropertyValue) -> {
        if (newPropertyValue) {

        } else {
            if (numberTextField.getText().isEmpty() || numberTextField.getText() == null
                    || Integer.parseInt(numberTextField.getText()) > 12) {
                numberTextField.setText("12");
            }
            System.out.println("Textfield 1 out focus");
        }

    });