【问题标题】:How to make TextFormatter work only if field is in focus?仅当字段处于焦点时,如何使 TextFormatter 工作?
【发布时间】:2018-10-08 05:02:22
【问题描述】:

我有一个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 仅在邮件字段处于焦点的情况下工作?

【问题讨论】:

标签: java validation javafx-8 text-formatting


【解决方案1】:

您可以使用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;
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多