JavaFX 绑定到多个属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20264480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX bind to multiple properties
提问by martin_dk
I have a simple fxml with a textfield and a button. I'd like to have the button disabled if the textfield is empty. So I insert something like the following in my controller:
我有一个带有文本字段和按钮的简单 fxml。如果文本字段为空,我想禁用该按钮。所以我在我的控制器中插入了如下内容:
@Override
public void initialize(URL url, ResourceBundle bundle) {
button.disableProperty().bind(textField.textProperty().isEqualTo(""));
}
..and that works fine. The problem is when I add a second textfield and would like my button to be disabled if either textfield is empty. What to do then? I tried the following, but that doesn't work:
..这很好用。问题是当我添加第二个文本字段并希望在任一文本字段为空时禁用我的按钮。那该怎么办呢?我尝试了以下方法,但这不起作用:
@Override
public void initialize(URL url, ResourceBundle bundle) {
button.disableProperty().bind(textField.textProperty().isEqualTo(""));
button.disableProperty().bind(textField2.textProperty().isEqualTo(""));
}
采纳答案by Andrey Chaschev
This is possible by binding to a boolean expression via Bindings
:
这可以通过以下方式绑定到布尔表达式Bindings
:
button.disableProperty().bind(
Bindings.and(
textField.textProperty().isEqualTo(""),
textField2.textProperty().isEqualTo("")));
回答by martin_dk
In addition to Andreys approach, I found that you can also do it like this:
除了安德烈斯的方法,我发现你也可以这样做:
BooleanBinding booleanBinding =
textField.textProperty().isEqualTo("").or(
textField2.textProperty().isEqualTo(""));
button.disableProperty().bind(booleanBinding);
回答by Korvin Gump
In addition to martin_dk answer, if you want to bind more than two properties you will get code like below, looks weird, but it works.
除了 martin_dk 答案,如果你想绑定两个以上的属性,你会得到如下代码,看起来很奇怪,但它有效。
BooleanBinding booleanBinding
= finalEditor.selectedProperty().or(
staticEditor.selectedProperty().or(
syncEditor.selectedProperty().or(
nativeEditor.selectedProperty().or(
strictEditor.selectedProperty()))));
abstractEditor.disableProperty ().bind(booleanBinding);