根据您的评论,您想要的是:当(选定的)值ComboBox
更改时,检查条件,如果不满足该条件,则设置回ComboBox
值相对于前一个值。
为此,您可以使用例如价值属性 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ComboBoxBase.html#valueProperty--具有侦听器的 ComboBox。侦听器主体只是检查条件,值更新嵌套在Platform.runLater{...}
block.
Example
在示例中它是一个ComboBox
只能设置为“二”。
ComboBox<String> cb = new ComboBox<String>(FXCollections.observableArrayList("One", "Two", "Three", "Four"));
cb.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
// If the condition is not met and the new value is not null: "rollback"
if(newValue != null && !newValue.equals("Two")){
Platform.runLater(new Runnable(){
@Override
public void run() {
cb.setValue(oldValue);
}});
}
}
});
...或者您可以使用选定的项目属性 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/SelectionModel.html#selectedItemProperty--也具有相同的结构...
cb.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)->{
if(newVal != null && !newVal.equals("Two")){
Platform.runLater(() -> cb.setValue(oldVal));
}
});
Note:这个解决方案并不是“阻止”选择,就像标题中那样:“回滚”已经执行的选择。