如何使用netbeans 7在java swing中选择当前组合框中的值时显示另一个组合框

时间:2014-01-16 10:28:14

标签: java swing jcombobox

如何在java swing中使用netbeans选择当前组合框中的值时可见另一个组合框7.假设我有一个标签名称country,然后从组合框1中选择一个国家(India)然后我需要另一个组合框(组合框2)出现与国家/地区(印度)相关联的州,我将从我的数据库中检索这些值。

1 个答案:

答案 0 :(得分:1)

尝试此示例并替换您的数据:

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);
                    }
                }

            }
        });
    }
}