Question

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);
Was it helpful?

Solution

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");

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top