Updating JComboBox

≡放荡痞女 提交于 2019-12-11 13:39:29

问题


So I'm using a JComboBox with an ArrayList:

protected JComboBox<String> jcb;
protected ArrayList<String> favourites;
favourites.add("Favourites");
favourites.add("-0.21 + 0.77");
favourites.add("-0.16 + -0.89");
jcb = new JComboBox(favourites.toArray());

This works fine and I can select each option and carry out the selected statements I need to do. However, when I wish to update the JComboBox, it does not update on my GUI. In another method I call:

favourites.add("10 + 4");
jcb.revalidate();
jcb.repaint();

I have Tested that the ArrayList has been updated (see below), however It doesn't show on my GUI, any suggestions? Thanks,

for (String s : favourites)
System.out.println(s);

回答1:


Swing is based on the MVC pattern. Thus use a model. Changes to the model will automatically update the JComboBox. For a deeper understanding in general read Swing Architecture Overview and for your case How to use ComboBoxes.

DefaultComboBoxModel favourites = new DefaultComboBoxModel();
favourites.addElement("Favourites");
favourites.addElement("-0.21 + 0.77");
favourites.addElement("-0.16 + -0.89");
jcb = new JComboBox(favourites);

in the other GUI method call

favourites.addElement("10 + 4");



回答2:


Swing components follow MVC pattern so you have to modify the jcombobox's model and then the model notifies the view that was changed. And as you are using DefaultComboBoxModel you can use addElement that will notify listeners and then the view get updated.

DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(new String[]{"Favourites","-0.21 + 0.77","-0.16 + -0.89"});
jcb = new JComboBox(model);

And when an event happen.

model.addElement("something");

Read more in How to use ComboBoxes



来源:https://stackoverflow.com/questions/22273311/updating-jcombobox

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