1355
1355

Reputation: 23

How to make visible another combo box on selection of a value in current combo box in java swing using netbeans 7

How to make visible another combo box on selection of a value in current combo box in java swing using netbeans 7.Suppose if i have a label name country and then select a country (India) from the combo box1 and then i need another combo box (combo box2)appear the states that is assosiated with country(India) which i will retrive the values from my database.

Upvotes: 0

Views: 1678

Answers (1)

SuRu
SuRu

Reputation: 739

try this example and replace your data:

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;

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

        box1.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent arg0) {
                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);
                    }
                }

            }
        });
    }
}

Upvotes: 1

Related Questions