Java Linking ComboBoxes

Hello Experts,

I'm trying to link together multiple comboboxes.  Say for example I create a combo box that lists baseball postions {"infield", "outfield"}...How could I set it up so that when I select the infield another combobox appears that shows {"First", "second", "Short", "Third"}
String[] positionStrings = {"Infield", "Outfield"};
        final JComboBox positionBox = new JComboBox(positionStrings);
        positionBox.setBorder(new TitledBorder("Position"));

//then select infield and display another list

String[] infieldPositionStrings = {"First", "Second", "Short", "Third"};
        final JComboBox infieldPositionBox = new JComboBox(infieldPositionStrings);
        infieldPositionBox.setBorder(new TitledBorder("Infield Position"));

Open in new window

Who is Participating?
gordon_vt02Connect With a Mentor Commented:
Add an ItemListener to the first combo box that changes the available selections in the second box when the value of the first box is modified.
final String[] POSITION_CATEGORIES = new String[] {

        final String[][] POSITION_SELECTIONS = new String[][] {
            { "Select a Category" },
            { "First", "Second", "Short", "Third", "Catcher" },
            { "Left", "Center", "Right" },
            { "Starter", "Reliever", "Closer" }
        final JComboBox categoryBox = new JComboBox(POSITION_CATEGORIES);
        final JComboBox positionBox = new JComboBox(POSITION_SELECTIONS[0]);

        categoryBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int index = categoryBox.getSelectedIndex();
                positionBox.setModel(new DefaultComboBoxModel(POSITION_SELECTIONS[index]));
                positionBox.setEnabled(index > 0);

Open in new window

islandguy10Author Commented:
islandguy10Author Commented:
Worked great, thanks a bunch!
no problem.  glad it helped!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.