在 JavaFX 中启用/禁用按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29641020/
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
Enabling/Disabling buttons in JavaFX
提问by user3505212
how do you disable buttons under a certain condition? For example, i have many text fields and buttons, when those text fields are empty one of my buttons should be disabled. i already have this code.
如何在特定条件下禁用按钮?例如,我有许多文本字段和按钮,当这些文本字段为空时,我的一个按钮应该被禁用。我已经有了这个代码。
if(txtID.getText().isEmpty()&&txtG.getText().isEmpty()
&&txtBP.getText().isEmpty()&&txtD.getText().isEmpty()
&&txtSP.getText().isEmpty()&&txtCons.getText().isEmpty()){
btnAdd.setDisable(true);
}
else{
btnAdd.setDisable(false);
}
is there an easier way to do this? Also if i add text into those areas shouldnt the button be re enable its self?
有没有更简单的方法来做到这一点?另外,如果我在这些区域添加文本,按钮不应该重新启用它自己吗?
采纳答案by ItachiUchiha
Create a BooleanBinding
using the textfield's textProperty()
and then bind it with the Button's disableProperty()
.
BooleanBinding
使用文本字段创建一个textProperty()
,然后将其与按钮的disableProperty()
.
For enabling the button if any of the textfields is not empty.
用于在任何文本字段不为空时启用按钮。
// I have added 2 textFields, you can add more...
BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
text2.textProperty().isEmpty());
button.disableProperty().bind(booleanBind);
For more than 2 textfields
对于超过 2 个文本字段
BooleanBinding booleanBind = Bindings.and(text1.textProperty().isEmpty(),
text2.textProperty().isEmpty()).and(text3.textProperty().isEmpty());
Or, a better approach is to use and
directly on the property:
或者,更好的方法是and
直接在属性上使用:
BooleanBinding booleanBind = text1.textProperty().isEmpty()
.and(text2.textProperty().isEmpty())
.and(text3.textProperty().isEmpty());
For enabling the button only if all of the textfields have text.
仅当所有文本字段都有文本时才启用按钮。
Just replace and
with or
.
只需替换and
为or
.
BooleanBinding booleanBind = text1.textProperty().isEmpty()
.or(text2.textProperty().isEmpty())
.or(text3.textProperty().isEmpty());
回答by Mohsen Bahaloo
in swing we can disable a button as follow:
JButton start = new JButton("Start");
start.setEnabled(false);
在 Swing 中,我们可以禁用一个按钮,如下所示:
JButton start = new JButton("Start");
start.setEnabled(false);
but in javaFX this function(setEnabled) changed to setDisabled, so we can use this code in javaFX:
start.setDisable(false);
但是在javaFX中这个函数(setEnabled)变成了setDisabled,所以我们可以在javaFX中使用这个代码:
start.setDisable(false);