下拉列表框 JComboBox
import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; class MyComboBox { private JFrame frame = new JFrame("Title"); private Container cont = frame.getContentPane(); private JComboBox jcb1 = null; private JComboBox jcb2 = null; private JPanel pan = new JPanel(); public MyComboBox () { frame.setLayout(new GridLayout(2,1)); String[] nations = {"中国","美国","英国","巴西","意大利"}; Vector<String> v = new Vector<>(); v.add("苹果"); v.add("香蕉"); v.add("葡萄"); v.add("鸭梨"); //实例化下拉列表框 this.jcb1 = new JComboBox(nations); this.jcb2 = new JComboBox(v); //为下拉列表框增加一个边框 this.jcb1.setBorder(BorderFactory.createTitledBorder("你最喜欢的国家?")); this.jcb2.setBorder(BorderFactory.createTitledBorder("你最喜欢的水果?")); cont.add(jcb1); cont.add(jcb2); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(1); } }); frame.setSize(300,200); frame.setVisible(true); } } public class JComboBoxDemo01 { public static void main(String[] args) { new MyComboBox(); } }
与List一样,在JComboBox中也可以使用ComboBoxModel接口来构造JComboBox中的列表内容,ComboBoxModel接口是ListModel接口的子类,除了继承JListModel中的所有操作方法之外,还增加了如下的方法:
-void setSelectedItem(Object anItem) 设置选项内容
-Object getSelectedItem() 返回选择项