gpt4 book ai didi

JavaFX ComboBox OnChangeListener 回滚变化

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:53:27 26 4
gpt4 key购买 nike

我正在尝试重置 ComboBox 的选择,如下所示:

// private ListView<MyEntityType> f_lItems

f_lItems.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<?> ov, Object t, Object t1) {
if (t1 != null && t1 instanceof MyEntityType) {

MyEntityType pv = (MyEntityType) t1;
// do some condition testing
if (condition) {
// accept
} else
// roll back to previous item
f_lItems.getSelectionModel().select((MyEntityType) t);
}
}
}
});

所以,在尝试将列表重置为旧值后,我得到了这个异常:

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException
at com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList.subList(Unknown Source)
at javafx.collections.ListChangeListener$Change.getAddedSubList(Unknown Source)
at com.sun.javafx.scene.control.behavior.ListViewBehavior.lambda$new$177(Unknown Source)
at javafx.collections.WeakListChangeListener.onChanged(Unknown Source)
at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(Unknown Source)

对于这种情况,我似乎没有得到 Lists/ObservableLists 的基本行为。

有没有人对我如何使这项工作有建议?

提前致谢亚当

最佳答案

根据您的评论,您想要的是:当 ComboBox 的(选定)值发生更改时,检查条件,如果不满足此条件,则将ComboBox 值到前一个。

为此,您可以使用例如 valueProperty ComboBox 的监听器。监听器主体只是检查条件,值更新嵌套在 Platform.runLater{...} block 中。

示例

在示例中,它是一个只能设置为“两个”的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);
}});
}
}
});

... 或者您可以使用 selectedItemProperty也具有相同的结构......

cb.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)->{
if(newVal != null && !newVal.equals("Two")){
Platform.runLater(() -> cb.setValue(oldVal));
}
});

注意:这个解决方案不是为了“阻止”选择,正如标题:“回滚”一个已经执行的选择。

关于JavaFX ComboBox OnChangeListener 回滚变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37931195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com