选中复选框时触发JAVAFX事件 [英] JAVAFX event triggered when selecting a check box
问题描述
我的JavaFx FXML应用程序存在问题。
My JavaFx FXML application has an issue.
当我在表单上选中一个复选框时,我想根据单击的复选框执行一个方法。有没有办法可以将复选框的名称传递给方法,以便我可以对它执行一些有条件的工作?
When I select a checkbox on a form, I want to execute a method based on the checkbox that was clicked. Is there any way that I can pass the name of the checkbox through to the method so I can perform some conditional work on it?
我有两个复选框,只有一个可以被选中。当我点击一个时,另一个应该被取消选择,反之亦然。显然下面的代码不起作用所以我希望传递被点击的对象的名称。
I have two checkboxes and only one can be selected. When I click on one, the other should be de-selected and vice versa. Obviously the code below will not work so I am looking to pass the name of the object that was clicked.
任何帮助都将不胜感激,
非常感谢。
Any help would be appreciated, many thanks.
@FXML private void updateRcs(){
if (chkRcsuri.isSelected()){
chkRcsuri2.setSelected(false);
}
if (chkRcsuri2.isSelected()){
chkRcsuri.setSelected(false);
}
}
推荐答案
您可以使用更改跟踪或使用JavaFX的事件处理机制。
使用这样的复选框,
You can use change tracking or use Event handling mechanism of JavaFX.
With checkboxes like this,
final CheckBox chk1 = new CheckBox("chk 1");
final CheckBox chk2 = new CheckBox("chk 2");
更改跟踪
chk1.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
chk2.setSelected(!newValue);
}
});
chk2.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
chk1.setSelected(!newValue);
}
});
使用事件处理
EventHandler eh = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (event.getSource() instanceof CheckBox) {
CheckBox chk = (CheckBox) event.getSource();
System.out.println("Action performed on checkbox " + chk.getText());
if ("chk 1".equals(chk.getText())) {
chk2.setSelected(!chk1.isSelected());
} else if ("chk 2".equals(chk.getText())) {
chk1.setSelected(!chk2.isSelected());
}
}
}
};
chk1.setOnAction(eh);
chk2.setOnAction(eh);
这篇关于选中复选框时触发JAVAFX事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!