1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import java.awt.Container; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector;
import javax.swing.AbstractListModel; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList;
class MyComboBoxModel extends AbstractListModel implements ComboBoxModel{ String nations[] = {"中国","美国","韩国","法国","英国"}; String item = null; @Override public int getSize() { // TODO 自动生成的方法存根 return this.nations.length; }
@Override public Object getElementAt(int index) { // TODO 自动生成的方法存根 return this.nations[index]; }
@Override public void setSelectedItem(Object anItem) { // TODO 自动生成的方法存根 this.item = (String) anItem; }
@Override public Object getSelectedItem() { // TODO 自动生成的方法存根 return this.item; } }
class MyComboBox{ private JFrame frame = new JFrame("窗体"); //定义窗体 private Container cont = frame.getContentPane(); //得到窗体容器 private JComboBox jcb1 = null; //定义下拉列表框 private JComboBox jcb2 = null; //定义下拉列表框 public MyComboBox(){ this.frame.setLayout(new GridLayout(2,2)); // String nations[] = {"中国","美国","韩国","法国","英国"}; // Vector<String> v = new Vector<String>(); //定义一个Vector集合 // v.add("元素1"); // v.add("元素2"); // v.add("元素3"); // this.jcb1 = new JComboBox(nations); // this.jcb2 = new JComboBox(v); this.jcb1 = new JComboBox(new MyComboBoxModel()); //实例化JComboBox //定义一个列表框的边框显示条 jcb1.setBorder(BorderFactory.createTitledBorder("哪个国家?")); // jcb2.setBorder(BorderFactory.createTitledBorder("Vector?")); jcb1.setMaximumRowCount(3); //最多显示3个选项 // jcb2.setMaximumRowCount(3); cont.add(this.jcb1); // cont.add(this.jcb2); cont.add(new JLabel("下拉列表框")); this.frame.setSize(330,200); this.frame.setVisible(true); this.frame.addWindowListener(new WindowAdapter(){ //加入事件监听 public void windowClosing(WindowEvent arg0) { //窗口关闭时触发,按下关闭按钮 // TODO 自动生成的方法存根 System.out.println("windowClosing-->窗口关闭"); System.exit(1); } }); } }
public class MyComboBox_demo {
public static void main(String[] args) { // TODO 自动生成的方法存根 new MyComboBox(); }
}
|