博为峰Java技术文章 ——JavaSESwing使用ComboBoxModel创建下拉列表框Ⅱ

    xiaoxiao2021-03-25  55

    博为峰小博老师:

    下面利用ComboBoxModel来创建一个下拉列表框实例,其代码如下所示:

    public class BWF {

    String[] s={"桃花","梅花","玫瑰","月季","茉莉","菊花"};

    public BWF(){

    JFrame jf=new JFrame("博为峰教育");

    Container contentPane=jf.getContentPane();

    ComboBoxModel<String> model=new UserDefineComboBoxModel();

    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 UserDefineComboBoxModel extends AbstractListModel<String> implements ComboBoxModel<String>{

    String item=null;

    public int getSize() {

    // TODO Auto-generated method stub

    return s.length;

    }

    public String getElementAt(int index) {

    // TODO Auto-generated method stub

    return s[index++];

    }

    public void setSelectedItem(Object anItem) {

    item=(String)anItem;

    }

    public Object getSelectedItem() {

    return item;

    }

    }

    }

    转载请注明原文地址: https://ju.6miu.com/read-16654.html

    最新回复(0)