Synchronized JList and JComboBox?

前端 未结 2 1779

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 an

相关标签:
2条回答
  • 2021-01-12 03:58

    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);
    
    0 讨论(0)
  • 2021-01-12 04:04

    You could have them share the same model, probably a DefaultComboBoxModel since it implements ListModel and thus should work for both the JComboBox and the 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);
          }
     }
    
    0 讨论(0)
提交回复
热议问题