import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxFrame extends JFrame{
private String []citys = {"HongKong","Shanghai","Beijing","Xi'an"};
private JComboBox combCity = new JComboBox();
private JButton b = new JButton("Add City");
private JTextField t = new JTextField(15);
private int count = 0;
public ComboBoxFrame(){
setSize(new Dimension(200,175));
combCity.addItem("Shenzhen");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(count < citys.length){
combCity.addItem(citys[count++]);
}
}
});
combCity.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = ((JComboBox)e.getSource()).getSelectedIndex();
t.setText("index:" + index);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(t);
getContentPane().add(combCity);
getContentPane().add(b);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
try{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}catch(Exception exception){
exception.printStackTrace();
}
ComboBoxFrame comboboxframe = new ComboBoxFrame();
comboboxframe.setVisible(true);
}
});
}
}
COPY过去运行吧!
actionPerformed