【问题标题】:Javafx ComboboxJavafx 组合框
【发布时间】:2021-05-25 01:47:40
【问题描述】:

我想使用 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);

Here is how the comboboxes all look

在对 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);
        }
    });

【问题讨论】:

    标签: javafx combobox observablelist


    【解决方案1】:

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

    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);
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 2017-02-08
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 2020-03-17
      • 2017-01-30
      • 2016-10-28
      相关资源
      最近更新 更多