naqi
naqi

Reputation: 55

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

Need help in Javafx text field focus property, I want to change the text in the text field if enter number greater than 12 using focus property when i focus out the text field then it must change the text inside to 12 code I am using is

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


    });

and the numberTextfield class is

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

so its working properly, it change text of the text field whenever i focus out, not after entering any text, or when i enter text less than 12.

Upvotes: 1

Views: 1361

Answers (1)

Gaali Prabhakar
Gaali Prabhakar

Reputation: 583

You have written condition wrongly. to write proper conditions, learn Trueth tables 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");
        }

    });

Upvotes: 2

Related Questions