Synchronized JList and JComboBox?

前端 未结 2 1778

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

提交回复
热议问题