import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class ComboBoxDemo extends JFrame {
 private Set<String> initCities =new HashSet<String>(Arrays.asList(
                      new String[]{"北京", "上海", "南京", "杭州","深圳"}));
 private Set<String> moreCities =new HashSet<String>(Arrays.asList(
                      new String[]{"济南", "沈阳", "合肥", "拉萨","重庆","兰州"}));
  private JTextField textField = new JTextField(20);
  private JComboBox<String> comboBox = new JComboBox<String>();
  private JButton button = new JButton("添加城市");

  public ComboBoxDemo(String title) {
    super(title);
    for(String city: initCities)
      comboBox.addItem(city);

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String city=(String)comboBox.getSelectedItem();
        if(moreCities.contains(city)){  //判断用户输入的城市是否在moreCities列表中
          comboBox.addItem(city);
          textField.setText("添加 "+city+" 成功");
          moreCities.remove(city);
        }else{
          textField.setText("添加 "+city+" 失败。不在可选值范围内。");
        }
      }
    });
    comboBox.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textField.setText("index: "+ comboBox.getSelectedIndex() + "   " +
        comboBox.getSelectedItem());
      }
    });

    comboBox.setEditable(true);  //使下拉列表可以被编辑
    textField .setEditable(false);
   
    setLayout(new FlowLayout());
    add(comboBox);
    add(button);
    add(textField);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
     new ComboBoxDemo("Hello");
  }
}


/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/
