import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JComboboxTest extends JFrame implements ActionListener {
private JComboBox box;
private String[] a = { "x", "y", "z" };
private JPanel p;
public JComboboxTest() {
box = new JComboBox(a);
box.addActionListener(this);
p = new JPanel();
p.add(box);
this.add(p);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == box) {
int index = box.getSelectedIndex();
switch (index) {
case 0:
//这里可以做别的事情,这样写只是为了告诉你有这个方法。
//box.getSelectedItem() 的返回值是 object
System.out.println(box.getSelectedItem().toString());
break;
case 1:
System.out.println(box.getSelectedItem().toString());
break;
case 2:
System.out.println(box.getSelectedItem().toString());
break;
}
}
}
public static void main(String[] args) {
new JComboboxTest();
}
}