Java Swing How to - Show second JComboBox on selection of first JComboBox








Question

We would like to know how to show second JComboBox on selection of first JComboBox.

Answer

import java.awt.FlowLayout;
//from w  ww .  j av a  2  s . co m
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String args[]) {
    String[] mainData = { "-Select-", "Sel 1", "Sel 2", "Sel 3" };
    String[] subData1 = { "Sub Sel 11", "Sub Sel 12", "Sub Sel 13" };
    String[] subData2 = { "Sub Sel 21", "Sub Sel 22", "Sub Sel 23" };
    String[] subData3 = { "Sub Sel 31", "Sub Sel 32", "Sub Sel 33" };
    DefaultComboBoxModel boxModel = new DefaultComboBoxModel();
    JComboBox box1 = new JComboBox(mainData), box2 = new JComboBox();
    JFrame frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.add(box1);
    frame.add(box2);
    box2.setVisible(false);
    box2.setModel(boxModel);
    frame.setBounds(200, 200, 500, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    box1.addItemListener(e -> {
      box2.setVisible(true);
      boxModel.removeAllElements();
      if (box1.getSelectedIndex() == 0) {
        box2.setVisible(false);
      } else if (box1.getSelectedIndex() == 1) {
        for (String s : subData1) {
          boxModel.addElement(s);
        }
      } else if (box1.getSelectedIndex() == 2) {
        for (String s : subData2) {
          boxModel.addElement(s);
        }
      } else if (box1.getSelectedIndex() == 3) {
        for (String s : subData3) {
          boxModel.addElement(s);
        }
      }
    });
  }
}