博为峰小博老师:
同JList一样,Java对于JComboBox也提供了另一个类,即DefaultComboBoxModel实体类。此类继承了AbstractListModel抽象类,也实现了ComboBoxModel接口,因此不需要再实现getSize(), getElementAt(), setSelectedltem()与getSelectedltem()方法。利用DefaultComboBoxModel类可以很方便地做到动态更改JComboBox的项目值。当没有必要自己定义特殊的ComboBoxModel时,使用DefaultComboBoxModel就显得非常方便。下面将通过一个实例来讲解这种创建方法,其程序代码如下所示:
public class BWF {
String[] s={"桃花","梅花","玫瑰","月季","茉莉","菊花"};
public BWF(){
JFrame jf=new JFrame("博为峰教育");
Container contentPane=jf.getContentPane();
ComboBoxModel<String> model=new Model(s);
JComboBox<String> combo=new JComboBox<String>(model);
combo.setBorder(BorderFactory.createTitledBorder("你最喜欢的花是那个?"));
contentPane.add(combo);
jf.pack();
jf.setVisible(true);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new BWF();
}
class Model extends DefaultComboBoxModel<String>{
private static final long serialVersionUID = 1L;
Model(String[] s){
for(int i=0;i<s.length;i++)
addElement(s[i]);
}
}
}