How to populate data in a JComboBox?

后端 未结 3 995
春和景丽
春和景丽 2021-01-16 00:07

I have created a GUI and have a database located externally in which I fetch data from. I am using the GUI builder in NetBeans to do this. Does anyone know of a simple way t

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-16 00:12

    When trying to add elements dynamically to a combo box, use MutableComboBoxModel.addElement

    JComboBox box = new JComboBox(new DefaultComboBoxModel());
    ....
    MutableComboBoxModel model = (DefaultComboBoxModel)box.getModel();
    while (rs.next()) {
        model.addElement(rs.getString("Name"));
    }
    

    To remove all elements you could also do

    ((DefaultComboBoxModel)box.getModel).removeAllElements();
    

    Using the model methods will fire the necessary changes to update the ui

提交回复
热议问题