Question

I would like to change the contents of the list of a JComboBox (like adding another list in place of and older one). Is there any way I might be able to do that? Thanks in advance!

Was it helpful?

Solution

If you want to be able to add and remove items from an existing combo box at runtime, the underlying data model for the combo box needs to be a MutableComboBoxModel

Google for that class for interface information and for examples of how to use it.

Note that if you want the user to type in new values, you also need to make the box editable.

You can find some links to examples here.

OTHER TIPS

I found this thread and came up with a quick (and probably dirty) solution:

oldComboBox.setModel(new JComboBox<>(new_items).getModel());

Of course you can. There are several methods for manipulating JComboBoxes using the default list model. Have a look at the remove* methods and add* methods:

http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.html

You can also replace the model in its entirety with setModel().

But after writing more and more user interfaces, I find it more useful to write a custom ComboBoxModel to wrap the data structure the ComboBox is presenting. This is more unit testable and cleaner, IMHO.

The Glazed Lists library is mighty helpful when you want to wire any sort of mutable list to a GUI control. It's a large-ish library which may not be appropriate for your project, but take a look at their screencasts and judge for yourself. It supports a lot of related stuff like filtering and auto-completion and can save you a lot of manual work.

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