简言之,比如说第一个框里有广东,江苏,安徽各省,第二个下拉框里有广东省的各个城市,比如广州,深圳之类的
见代码:
import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; public class MyFrame extends JFrame { // 声明下来列表JComboBox private JComboBox choice1; private JComboBox choice2; //定义一个数组 private static String[] s1 = {"中国","美国","日本","澳大利亚","法国","德国","英国"}; private static String[][] s2 = { {"北京","上海","广州","深圳"}, {"华盛顿","纽约","芝加哥","旧金山"}, {"东京","大阪","名古屋","北海道"}, {"悉尼","堪培拉","珀斯"}, {"巴黎","南特","德勒","鲁昂"}, {"柏林","华沙","卢布林","波兹南"}, {"伦敦","曼切斯特","诺丁汉","牛津"} }; public MyFrame(String title){ super(title); // 设置布局管理 getContentPane().setLayout(new GridLayout(2,2,0,0)); // 创建标签 JLabel label1 = new JLabel("选择你喜欢的国家:"); label1.setHorizontalAlignment(SwingConstants.RIGHT); getContentPane().add(label1); // 实例化JComboBox对象 choice1 = new JComboBox(s1); // 为组合框的选择动作注册监听事件,当此组合框的选择有变化时,另一个组合框自动更新内容 choice1.addActionListener(e -> { choice2.removeAllItems(); JComboBox cb = (JComboBox) e.getSource(); // 获得选择项目 String itemString = (String) cb.getSelectedItem(); System.out.println(itemString); int index = choice1.getSelectedIndex(); for(int i=0; i<s2[index].length; i++) { choice2.addItem(s2[index][i]); } }); getContentPane().add(choice1); // 创建标签 JLabel label2 = new JLabel("选择城市:"); label2.setHorizontalAlignment(SwingConstants.RIGHT); getContentPane().add(label2); // 实例化JComboBox对象 choice2 = new JComboBox(s2[0]); // 注册Action事件监听,采用Lambda表达式 choice2.addItemListener(e -> { // 获得选择项目 if (e.getStateChange() == ItemEvent.SELECTED){ // 获得选择项目 String itemString = (String) e.getItem(); System.out.println(itemString); } }); getContentPane().add(choice2); // 设置窗口大小 setSize(400,150); // 设置窗口可见 setVisible(true); } }
调用代码:
public class HelloWorld { public static void main(String[] args) { MyFrame myFrame = new MyFrame("下拉列表"); } }
运行结果: