省市区三级联动
1.创建两个类的项目,先运行在修改中理解。重要的是要自己写一遍,理解一句代码最好的方法就是替换,删除观察区别。
package linkge;
import javax.swing.;
import java.awt.event.;
public class ItemEvents extends JFrame implements ItemListener {
JComboBox Province;
JComboBox City;
JComboBox Area;
public ItemEvents() { //构造方法
this.setTitle("省市区三级联动");
this.setSize(300, 400);
this.setLayout(null);
Province = new JComboBox();
Province.addItem("请选择省份 ");
Province.addItem("陕西省");
Province.addItem("安徽省");
Province.setSize(120, 30);
Province.setLocation(30, 30);
Province.addItemListener(this);
this.add(Province);
City = new JComboBox();
City.addItem("请选择城市");
City.addItem(" ");
City.setSize(120, 30);
City.setLocation(30, 80);
this.add(City);
Area = new JComboBox();
Area.setSize(120, 30);
Area.setLocation(30, 130);
Area.addItem("请选择县区");
this.add(Area);
Area.addItem(" ");
this.setVisible(true);
}
public void itemStateChanged(java.awt.event.ItemEvent e) {
String temp = ((JComboBox) e.getSource()).getSelectedItem().toString();
if (temp.equals("陕西省")) {
City.removeItemListener(this);
City.removeAllItems();
City.addItemListener(this);
String[] city = { "西安市", "咸阳市", };
for (int i = 0; i < city.length; i++) {
City.addItem(city[i]);
}
}
if (temp.equals("安徽省")) {
City.removeItemListener(this);
City.removeAllItems();
City.addItemListener(this);
String[] city = { "合肥市", "黄山市"};
for (int i = 0; i < city.length; i++) {
City.addItem(city[i]);
}
}
if (temp.equals("西安市")) {
Area.removeItemListener(this);
Area.removeAllItems();
Area.addItemListener(this);
String[] area = { "未央区", "雁塔区", "新城区" }; //动态数组存储地名
for (int i = 0; i < area.length; i++) {
Area.addItem(area[i]);
}
}
if (temp.equals("咸阳市")) {
Area.removeItemListener(this);
Area.removeAllItems();
Area.addItemListener(this);
Area.removeAllItems();
String[] area = { "秦都区", "渭滨区", "长武县", "武功县", "泾阳县" };
for (int i = 0; i < area.length; i++) {
Area.addItem(area[i]);
}
}
if (temp.equals("合肥市")) {
Area.removeItemListener(this);
Area.removeAllItems();
Area.addItemListener(this);
String[] area = { "庐阳区", "蜀山区" };
for (int i = 0; i < area.length; i++) {
Area.addItem(area[i]);
}
}
if (temp.equals("黄山市")) {
Area.removeItemListener(this);
Area.removeAllItems();
Area.addItemListener(this);
Area.removeAllItems();
String[] area = { "徽州区", "黄山区" };
for (int i = 0; i < area.length; i++) {
Area.addItem(area[i]);
}
}
if (temp.equals(" ")) {
Area.removeItemListener(this);
Area.removeAllItems();
Area.addItem("请选择市区");
City.removeItemListener(this);
City.removeAllItems();
City.addItem("请选择省份");
}
}
}
package linkge;
public class Test {
public static void main (String[]args)
{
ItemEvents test = new ItemEvents();
}
}
2.运行如图

是不是看到这里心动了呢,快点写出自己的家乡吧!
本文介绍了如何在Java中创建省市区三级联动效果。通过创建两个类并实现ItemListener接口,理解代码运行过程,实现GUI界面中下拉菜单的联动交互。读者被鼓励亲手实践,写出自己的家乡信息。
8393

被折叠的 条评论
为什么被折叠?



