javafx - 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);
}
});
解决方案
我没有测试下面的代码,但你可以用这样的东西来做......
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);
}
});
}
推荐阅读
- ansible - 通过在 Jinja2/ansible 之间添加一个字符串来合并 2 个列表
- android - OPEN_APP_FEATURE 操作无法通过语音命令运行 [通过应用程序操作测试工具完美运行]
- python - Python tkinter filedialog在mac上禁用菜单
- python - Python yield 不等待阻塞调用
- spring - 如何使用 log4j appenders 写入特定文件
- kotlin - 使用主构造函数时的 Kotlin getter / setter
- javascript - 我需要使用组件类中填充的循环动态地将对象数组分配给有角度的图像轮播容器
- css - 在 VueJS 上使用 Element UI 上传单个文件
- elasticsearch - 控制为 ES 打开的文件描述符过多
- java - FirebaseRecylerOptions 的实现是什么(不是 FirebaseRecylerAdapter)