【问题标题】:JavaFX: How to bind text field "style property" to text property matching some patternJavaFX:如何将文本字段“样式属性”绑定到匹配某些模式的文本属性
【发布时间】:2023-03-12 01:55:01
【问题描述】:

在我的应用程序中,我有一个屏幕,其中包含我需要验证的三个字段和一个保存按钮。

我将保存按钮“禁用属性”绑定到匹配某些模式的字段“文本属性”(本例中的简化模式无关紧要):

public void initialize(){
    saveNetworkBtn.disableProperty()
            .bind(textPropertyBindingPattern(ipInp, Pattern.compile("[0-9]{3}"))
                    .or(textPropertyBindingPattern(subnetInp, Pattern.compile("[0-9]{3}")))
                    .or(textPropertyBindingPattern(gatewayInp, Pattern.compile("[0-9]{3}"))));
}

private BooleanBinding textPropertyBindingPattern(TextField textField, Pattern pattern ) {
    return Bindings.createBooleanBinding(() ->
            !pattern.matcher(textField.getText()).matches(), textField.textProperty());
}

这样保存按钮就会被锁定,直到所有值都正确:

但我还需要用一些红色边框突出显示不正确的字段,例如

-fx-border-color: red;

我的主要目标是在一个地方处理这个问题,而不是添加多个侦听器。 是否可以在上面的代码中以某种方式对此进行处理,或者我需要为每个字段添加侦听器?

【问题讨论】:

  • 我建议单独绑定每个属性。所以是的,将字段的边框或样式属性绑定到其文本。如果你有很多这样的字段,子类TextField 并将这个绑定行为直接添加到它。这样您就不必单独绑定每个字段。

标签: java user-interface javafx fxml


【解决方案1】:

通过在绑定中添加一个监听器来解决,它为接收到的文本字段添加一个样式:

private BooleanBinding textPropertyBindingPattern(TextField textField, Pattern pattern) {
    BooleanBinding binding = Bindings.createBooleanBinding(() ->
            !pattern.matcher(textField.getText()).matches(), textField.textProperty());

    applyValidationClass(textField, binding.get());

    binding.addListener((obs, oldValue, newValue) -> {
        applyValidationClass(textField, newValue);
    });
    return binding ;
}

private void applyValidationClass(TextField textField, boolean isInvalid) {
    textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("incorrect-value"), isInvalid);
}

和 CSS 文件中描述的“错误值”:

TextField:incorrect-value {
    -fx-border-color: red;
}

可视化:https://www.screencast.com/t/4NKEjjopvaE7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多