Java Swing How to - Link two JComboBox








Question

We would like to know how to link two JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
//from   ww  w . ja v a 2  s . co  m
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener {
  private JComboBox mainComboBox;
  private JComboBox subComboBox;
  private Hashtable subItems = new Hashtable();

  public Main() {
    String[] items = { "Select Item", "Color", "Shape", "Fruit" };
    mainComboBox = new JComboBox(items);
    mainComboBox.addActionListener(this);

    getContentPane().add(mainComboBox, BorderLayout.WEST);

    subComboBox = new JComboBox();
    getContentPane().add(subComboBox, BorderLayout.EAST);

    String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
    subItems.put(items[1], subItems1);

    String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
    subItems.put(items[2], subItems2);

    String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
    subItems.put(items[3], subItems3);
  }

  public void actionPerformed(ActionEvent e) {
    String item = (String) mainComboBox.getSelectedItem();
    Object o = subItems.get(item);

    if (o == null) {
      subComboBox.setModel(new DefaultComboBoxModel());
    } else {
      subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
    }
  }

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