首页 > 解决方案 > Javafx 组合框

问题描述

我想使用具有相同选择集的 3 个组合框。一旦从其中一个组合框中选择了一个,则该选择在其他组合框中被消除,或者它们都保持相同的选择,但一次只允许一个特定的选择。所以对于第二个选项,如果盒子一选择“黄色”,然后盒子二选择“黄色”,那么盒子一现在正在等待选择。我尝试了一些使用组合框、Jcombobox 和 observablelists/observableitemlist 的方法,但仍然无法弄清楚。我想也许可以使用一个听众,但也被难住了。

我这样设置我的代码

    ObservableList<String> c = FXCollections.observableArrayList("Blue", "Green", "Grey", "Red", "Black", "Yellow");

    ComboBox col = new ComboBox(c);

    ComboBox col2 = new ComboBox(c);

    ComboBox col3 = new ComboBox(c);

这是组合框的所有外观

在对 Sai Dandem 的帮助进行了一些测试和修改之后,这是任何关注这篇文章的人的最终代码。他的代码大部分都可以工作,但存在空指针异常问题,并且代码有时无法按需要清除所有框。

    col.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
        if(col2.getSelectionModel().getSelectedItem() != null && col2.getSelectionModel().getSelectedItem().equals(val)) {
            col2.setValue(null);
        }
        if(col3.getSelectionModel().getSelectedItem() != null && col3.getSelectionModel().getSelectedItem().equals(val)) {
            col3.setValue(null);
        }
    });
    col2.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
        if(col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem().equals(val)) {
            col.setValue(null);
        }
        if(col3.getSelectionModel().getSelectedItem() != null && col3.getSelectionModel().getSelectedItem().equals(val)) {
            col3.setValue(null);
        }
    });
    col3.getSelectionModel().selectedItemProperty().addListener((obs, old, val)-> {
        if(col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem() != null && col.getSelectionModel().getSelectedItem().equals(val)) {
            col.setValue(null);
        }
        if(col2.getSelectionModel().getSelectedItem() != null && col2.getSelectionModel().getSelectedItem().equals(val)) {
            col2.setValue(null);
        }
    });

标签: javafxcomboboxobservablelist

解决方案


我没有测试下面的代码,但你可以用这样的东西来做......

col.valueProperty().addListener((obs, old, val)->updateValue(val, col));
col2.valueProperty().addListener((obs,old,val)->updateValue(val,col2));
col3.valueProperty().addListener((obs,old,val)->updateValue(val,col3));

private void updateValue(String val, ComboBox combo){
    Stream.of(col,col2,col3).forEach(c->{
        if(c!=combo && c.getValue().equals(val){
            c.setValue(null);
        }
    });
}

推荐阅读