Dynamically change JComboBox

点点圈 提交于 2019-11-29 01:11:38
DefaultComboBoxModel model = new DefaultComboBoxModel( yourStringArray );
comboBox.setModel( model );

You have a couple of options. You can use removeAllItems() (or one of the other remove methods) and addItem(Object anObject) to manipulate the selectable objects. Or you could implement a ComboBoxModeland allow it to serve up data from your array.

This is the demo for illustrating default combo box model

public class ComboPanel extends JPanel {

    JComboBox jcbo;
    // this is constructor
    public ComboPanel(ArrayList<String> items) {
        jcbo = new JComboBox();
        // getting exiting combo box model
        DefaultComboBoxModel model = (DefaultComboBoxModel) jcbo.getModel();
        // removing old data
        model.removeAllElements();

        for (String item : items) {
            model.addElement(item);
        }

        // setting model with new data
        jcbo.setModel(model);
        // adding combobox to panel
        this.add(jcbo);    
    }
}

I hope this will help little :)

It also works without DefaultComboBoxModel...

JComboBox op=new JComboBox(new String[] {"d","e","f"});
op.removeAllItems();
String[] new_entries=new String[] {"a","b","c"}
for (String s : new_entries) {
     op.insertItemAt(s, op.getItemCount());
}
op.setSelectedIndex(0);

Guess which values you'll see...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!