开发者

Synchronized JList and JComboBox? [duplicate]

开发者 https://www.devze.com 2023-02-09 04:08 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Synchronized JList and JComboBox?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Synchronized JList and JComboBox?

Hello,

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


You're creating two models in your code. When you construct the new DefaultComboBoxModel by passing in the listModel contents you are constructing a second model that just starts with the same contents as the first. They won't update the same. You want the two components to share a model. In other words...

JList list = new JList();
JComboBox comboBox = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
// add items to listModel...
list.setModel(listModel);
comboBox.setModel(listModel);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号