Java Swing How to - Create JComboBoxes with Shared Data Model








Question

We would like to know how to create JComboBoxes with Shared Data Model.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from   w w  w . jav a 2  s.  c o  m*/
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel implements ActionListener{
  JComboBox<String> combo1 = new JComboBox<>(new String[] { "Course 1",
      "Course 2", "Course 3" });
  JComboBox<String> combo2 = new JComboBox<>();
  ComboBoxModel<String>[] models = new ComboBoxModel[3];

  public Main() {
    models[0] = new DefaultComboBoxModel<>(new String[] { "A1", "A2" });
    models[1] = new DefaultComboBoxModel<>(new String[] { "B1", "B2", "B3",
        "B4" });
    models[2] = new DefaultComboBoxModel<>(new String[] { "C1", "C2" });

    combo2.setModel(models[0]);
    this.add(combo1);
    this.add(combo2);
    combo1.addActionListener(this);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    int i = combo1.getSelectedIndex();
    combo2.setModel(models[i]);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}