Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized JList and 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()));
like image 946
Vicky Chijwani Avatar asked Feb 08 '11 23:02

Vicky Chijwani


People also ask

What is the difference between JComboBox and JList?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

What is a JComboBox?

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .

What is the purpose of JList?

JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .

Which listener is implemented for JComboBox?

Adds a PopupMenu listener which will listen to notification messages from the popup portion of the combo box. Initializes the editor with the specified item. Sets the properties on this combobox to match those in the specified Action . This method is public as an implementation side effect.


1 Answers

Your models - the ListModel for the list and the ComboboxModel for the combobox - need to be synchronized.

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);
like image 75
Paŭlo Ebermann Avatar answered Sep 20 '22 00:09

Paŭlo Ebermann