条件绑定

Wer*_*erb 5 java javafx javafx-8

我是JavaFx的新手,我正在创建一个用户必须填写一些表单的应用程序,我想用绑定"预先验证"它们.像这些元素一样的简单东西可以是空的,或者其中一些只能包含数字.这是我到目前为止:

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

这是我的isNumber方法:

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

但无论我在TextField中输入什么内容,按钮都会被禁用.

任何帮助是极大的赞赏.

UPDATE

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

Mic*_*mpe 15

你的表情有点偏.

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

saveBtn.disableProperty().bind(Bindings.when(
        departureHourText.textProperty().isNotEqualTo(""))
        .then(false)
        .otherwise(true));
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常.在文本框中添加字符串时,您将获得一个按钮切换事件.

saveBtn.disableProperty().bind(Bindings.when(
        isNumber(departureHourText.getText()))
        .then(false)
        .otherwise(true));
Run Code Online (Sandbox Code Playgroud)

上面的代码使得按钮始终被卡在禁用状态.我们来研究一下原因.

让我们在方法isNumber()中添加一个print语句:

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

如果我们看一下当我们开始输入时执行它的时候,我们发现它只在我们最初声明绑定时被调用!这是因为你的方法不知道何时被调用,所以绑定只能在最初看到它,因为它是假的,因为字段中没有数字.

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

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

首先,让我们制作一个新模式:

Pattern numbers = Pattern.compile("[0-9]+");
Run Code Online (Sandbox Code Playgroud)

然后创建绑定功能:

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

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

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

希望有所帮助!