package javademo; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class combobox extends JFrame{ protected Container container; protected JComboBox colorcb; protected JPanel top; protected JTextField inf; protected JLabel ll; protected String colorSelected; public combobox() { container=this.getContentPane(); ll=new JLabel("请选择颜色"); colorcb=new JComboBox();//颜色检索下拉列表 colorcb.addItem(""); colorcb.addItem("红色"); colorcb.addItem("绿色"); colorcb.addItem("蓝色"); colorcb.addItemListener(new ColorSelectedListener());//注册事件监听者 inf=new JTextField(15); top=new JPanel(); top.setLayout(new FlowLayout(FlowLayout.LEFT)); top.add(ll); top.add(colorcb); top.add(inf); this.add(BorderLayout.NORTH,top); this.setTitle("JComboBox演示程序"); this.setSize(600,450); this.show(); } class ColorSelectedListener implements ItemListener{ public void itemStateChanged(ItemEvent event) { if( event.getStateChange()==ItemEvent.SELECTED) { colorSelected=(String)colorcb.getSelectedItem(); inf.setText("你选择的颜色是"+colorSelected); } } } public static void main(String []args) { new combobox(); } }
运行结果: