同步JList和JComboBox? [英] Synchronized JList and JComboBox?
问题描述
在Java Swing中,对于 JList
和 JComboBox
的最佳方式是什么?数据,即在任何给定的时间点拥有相同的项目列表?基本上,如果我向其中添加项目(或从中移除项目),则另一项应自动反映更改。
In Java Swing, what's the best way for a JList
and a JComboBox
to be synchronized in terms of the data, i.e., to have the same list of items at any given point of time? Basically, if I add items to (or remove items from) one, the other should reflect the change automatically.
我已尝试执行以下操作,但它没有似乎工作:
I've tried doing the following, but it doesn't seem to work:
JList list = new JList();
JComboBox comboBox = new JComboBox();
DefaultListModel listModel = new DefaultListModel();
// add items to listModel...
list.setModel(listModel);
comboBox.setModel(new DefaultComboBoxModel(listModel.toArray()));
推荐答案
您的模型 - 列表的ListModel和ComboboxModel对于组合框 - 需要同步。
Your models - the ListModel for the list and the ComboboxModel for the combobox - need to be synchronized.
在一般情况下,这意味着编写一个特殊的模型实现,但在你的情况下你运气好:事实上是DefaultComboBoxModel实现ListModel,因此您只需为组件使用相同的模型对象。
In the general case this would mean writing a special implementation of the models, but in your case you have luck: DefaultComboBoxModel in fact implements ListModel, so you simply can use the same model object for both your components.
JList list = new JList();
JComboBox comboBox = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
// add items to listModel...
list.setModel(listModel);
comboBox.setModel(listModel);
这篇关于同步JList和JComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!