Synchronized JList and JComboBox?

In Java Swing, the best way for JList and JComboBox synchronize in terms of data, i.e. have the same list of items at any given time? Basically, if I add elements (or delete elements) one, the other should reflect this change automatically.

I tried to do the following, but it does not 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())); 
+8
java swing jcombobox jlist
source share
2 answers

Your models — ListModel for list and ComboboxModel for combobox — must be in sync.

In the general case, this would mean writing a special implementation of models, but in your case you are in luck: DefaultComboBoxModel actually implements ListModel, so you can just use the same model object for your components.

 JList list = new JList(); JComboBox comboBox = new JComboBox(); DefaultComboBoxModel listModel = new DefaultComboBoxModel(); // add items to listModel... list.setModel(listModel); comboBox.setModel(listModel); 
+10
source share

Perhaps you have the same model, perhaps DefaultComboBoxModel, because it implements ListModel and therefore should work for both JComboBox and JList. For example:

  import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class ShareComboModel { private static final int TIMER_DELAY = 2000; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createGui(); } }); } private static void createGui() { String[] data = {"Fe", "Fi", "Fo", "Fum"}; final DefaultComboBoxModel model = new DefaultComboBoxModel(data); JComboBox combobox = new JComboBox(model); JList jlist = new JList(model); new Timer(TIMER_DELAY, new ActionListener() { private int count = 0; public void actionPerformed(ActionEvent e) { model.addElement("count: " + count); count++; } }).start(); JPanel comboPanel = new JPanel(); comboPanel.add(combobox); JPanel listPanel = new JPanel(); listPanel.add(new JScrollPane(jlist)); JPanel panel = new JPanel(new GridLayout(1, 0)); panel.add(comboPanel); panel.add(listPanel); panel.setPreferredSize(new Dimension(400, 200)); JFrame frame = new JFrame("App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 
+5
source share

All Articles