需要帮助在JavaFx Textfield焦点属性关于改变焦点后的文本



需要帮助在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");
        }

    });

和numberTextfield类是

    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。

您写错了条件。要编写合适的条件,请学习true表。参见

    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");
        }
    });

最新更新