Java Swing实现学院和专业之间的二级联动
import java.applet.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.*;
import javax.swing.*;
public class ItemTest extends JFrame implements ItemListener
{
JComboBox colCom;//学院
JComboBox proCom;//专业
JLabel jLabel1 = new JLabel();
JLabel jLabel2 = new JLabel();
String str[][]={{"物联网","网络","计科"},{"自动化","控制","电机"},{"物流","机械","电子"}};
public ItemTest()
{
this.setSize(300,300);
this.setLayout(null);
colCom=new JComboBox();
proCom=new JComboBox();
jLabel1.setFont(new java.awt.Font("Dialog", Font.BOLD, 13));
jLabel1.setText("学院");
jLabel1.setBounds(new Rectangle(20,66, 55, 20));
jLabel2.setFont(new java.awt.Font("Dialog", Font.BOLD, 13));
jLabel2.setText("专业");
jLabel2.setBounds(new Rectangle(20,106, 55, 20));
colCom.setFont(new java.awt.Font("Dialog", Font.BOLD, 13));
colCom.setBounds(new Rectangle(0, 0, 55, 18));
colCom.addItem("电智");
colCom.addItem("电控");
colCom.addItem("机电");
proCom.setFont(new java.awt.Font("Dialog", Font.BOLD, 13));
proCom.setBounds(new Rectangle( 62,103,70,25));
colCom.setSize(70,30);
colCom.setLocation(60, 60);
colCom.addItemListener(this);
this.add(colCom);
this.add(proCom);
this.add(jLabel1);
this.add(jLabel2);
this.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
System.out.println("ok");
JComboBox com=(JComboBox)e.getSource();
if(com.getSelectedItem().toString().equals("电智"))
{
proCom.removeAllItems();
for(int i=0;i<3;i++){
proCom.addItem(str[0][i]);
}
}
else
{
if(com.getSelectedItem().toString().equals("电控"))
{
proCom.removeAllItems();
for(int i=0;i<3;i++){
proCom.addItem(str[1][i]);
}
}
else
{
proCom.removeAllItems();
for(int i=0;i<3;i++){
proCom.addItem(str[2][i]);
}
}
}
}
public static void main(String[] args) {
ItemTest main=new ItemTest();
}
}