如何使 TextFormatter 仅在字段处于焦点时才工作?

How to make TextFormatter work only if field is in focus?

我有一个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;
}));

由于初始邮件存储在数据库中,我不想为它显示正确的图标,但前提是用户尝试调整它。是否可以使 TextFormatter 仅在邮件字段处于焦点时才起作用?

您可以使用isFocused()函数:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#isFocused--

在 TextFormatter 的开头,您可以这样做:

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

完整示例:

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