JavaFX ComboBox OnChangeListener回滚更改。

5

我正在尝试重置 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 的基本行为。

有人有建议如何使这个工作吗?

提前致谢 Adam


你所说的“重置 ComboBox 的选择”具体是什么意思?你想让 ComboBox 每次选择另一个选项时都默认选择某个特定的项目吗? - SpaceCore186
你想要做什么?举个例子,使用这种方法可能会导致StackOverflowError错误... - GOXR3PLUS
假设所选索引为4。用户将索引设置为6。在更改处理程序中,我想将索引设置回4,因为有一些内部原因。实际上,我想要实现“您确定要更改选择吗”的功能。另一方面,我认为这不应该是正确的方法。也许我必须首先防止更改事件的发生。 - PAWL
1个回答

4
根据您的评论,您想要实现的是:当更改ComboBox的(选定)值时,检查条件,如果不符合条件,则将ComboBox值设置回先前的值。
为此,您可以使用ComboBoxvalueProperty与监听器。 监听器主体只是用于检查条件,而值更新嵌套在Platform.runLater{...}块中。 示例 在此示例中,ComboBox仅可设置为“Two”。
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));
    }
});

注意: 这个解决方案不是为了“防止”选择,而是像标题中所说的:“回滚”已经执行的选择。


这正是我正在寻找的。谢谢! - PAWL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接