条件绑定

Conditional Binding

我是 JavaFx 的新手,我正在创建一个应用程序,用户必须在其中填写一些表格,我想 "pre validate" 使用绑定。像 none 这样简单的元素可以是空的,或者其中一些只能包含数字。这是我目前所拥有的:

saveBtn.disableProperty().bind(Bindings.when(
            departureHourText.textProperty().isNotEqualTo("")
                    .and(isNumber(departureHourText.getText())))
            .then(false)
            .otherwise(true));

这是我的 isNumber 方法:

private BooleanProperty isNumber(String string) {
    return new SimpleBooleanProperty(string.matches("[0-9]+"));
}

但是无论我在 TextField 中输入什么内容,该按钮都一直处于禁用状态。

非常感谢任何帮助。

更新

当我计算这个表达式时:departureHourText.textProperty().isNotEqualTo("") 结果将是:BooleanBinding [invalid]

你的表情有点不对劲

让我们尝试测试您的逻辑语句的两个部分:

saveBtn.disableProperty().bind(Bindings.when(
        departureHourText.textProperty().isNotEqualTo(""))
        .then(false)
        .otherwise(true));

以上代码工作正常。当您将字符串添加到文本框时,您将获得一个按钮切换事件。

saveBtn.disableProperty().bind(Bindings.when(
        isNumber(departureHourText.getText()))
        .then(false)
        .otherwise(true));

以上代码使按钮始终处于禁用状态。让我们调查一下原因。

让我们在 isNumber() 方法中添加一条打印语句:

private BooleanProperty isNumber(String string) {
System.out.println("This was called");
return new SimpleBooleanProperty(string.matches("[0-9]+"));
}

如果我们在开始输入时查看它何时执行,我们会发现它仅在我们最初声明绑定时被调用!这是因为您的方法不知道何时被调用,所以绑定只会在最初看到它,当它为 false 时因为字段中没有数字。

我们需要做的是找到一种方法,以便当我们的文本 属性 更新时,它知道改变状态。如果我们以 isNotEqualTo() 为例,我们会发现我们可能想要寻找一种方法来以某种方式创建新的 BooleanBinding。

现在,我找到了一个函数,我从 github link (https://gist.github.com/james-d/9904574) 修改而来。 link 指示我们如何从正则表达式模式创建新的 BooleanBinding。

首先,让我们制作一个新图案:

Pattern numbers = Pattern.compile("[0-9]+");

然后创建绑定函数:

BooleanBinding patternTextAreaBinding(TextArea textArea, Pattern pattern) {
BooleanBinding binding = Bindings.createBooleanBinding(() -> 
    pattern.matcher(textArea.getText()).matches(), textArea.textProperty());
return binding ;
}

因此,我们现在可以做您想做的事了! 我们只是将您之前的函数更改为我们的新 patternTextAreaBinding(TextArea textArea, Pattern pattern) 函数并传入我们的两个值,即您要跟踪的 textArea 和您要遵循的模式(我将模式称为上面的数字) .

saveBtn.disableProperty().bind(Bindings.when(
        departureHourText.textProperty().isNotEqualTo("")
                .and(patternTextAreaBinding(departureHourText,numbers)))
        .then(false)
        .otherwise(true));

希望对您有所帮助!

不知是否可以不用when来写表达式? If (x) then false else true; 似乎是多余的,可以使用 not (x)...

进行简化

可以选择只使用 .not(),如下所示: .bind(departureHourText.textProperty().isNotEqualTo("").and(patternTextAreaBinding(departureHourText,numbers))).not())