0

I have a TextFormatter:

mailTextField.setTextFormatter(new TextFormatter<>(change -> {
    int maxLength = 100;

    if (change.isAdded()) {
        if(change.getControlNewText().length()>maxLength){
            if(change.getText().length()==1){
                change = null;
                System.out.println("Reached max!");
            }else{
                int allowedLength = maxLength - change.getControlText().length();
                change.setText(change.getText().substring(0, allowedLength));
                System.out.println("Cut paste!");
            }
        }

        if(change!=null){
            System.out.println("Mail check: "+change.getControlNewText());
            if(Validation.mail(change.getControlNewText())){
                showCorrectIcon(mailTextField);
                }else{
                showErrorIcon(mailTextField);
            }
        }
    }
    return change;
}));

Since initial mail is stored in database, I don't want to show correct icon for it, but only if user tries to adjust it. Is it possible to make TextFormatter work only in case mail field is in focus?

xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37
Alyona
  • 1,682
  • 2
  • 21
  • 44
  • Maybe you change the TextFormatter on Focus changed. Look at https://stackoverflow.com/questions/16549296/how-perform-task-on-javafx-textfield-at-onfocus-and-outfocus. – Ralf Renz Apr 27 '18 at 11:57

1 Answers1

0

You can make use of the isFocused() function: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#isFocused--

At the start of your TextFormatter you could do:

if (!mailTextField.isFocused()) {
    return change;
}

Full example:

mailTextField.setTextFormatter(new TextFormatter<>(change -> {
    if (!mailTextField.isFocused()) {
        return change;
    }

    int maxLength = 100;

    if (change.isAdded()) {
        if(change.getControlNewText().length()>maxLength){
            if(change.getText().length()==1){
                change = null;
                System.out.println("Reached max!");
            }else{
                int allowedLength = maxLength - change.getControlText().length();
                change.setText(change.getText().substring(0, allowedLength));
                System.out.println("Cut paste!");
            }
        }

        if(change!=null){
            System.out.println("Mail check: "+change.getControlNewText());
            if(Validation.mail(change.getControlNewText())){
                showCorrectIcon(mailTextField);
                }else{
                showErrorIcon(mailTextField);
            }
        }
    }
    return change;
}));
explv
  • 2,709
  • 10
  • 17