acostache
acostache

Reputation: 2275

Changing the Contents of the JComboBox

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!

Upvotes: 13

Views: 25125

Answers (5)

pal
pal

Reputation: 949

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

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

Upvotes: 5

Barend
Barend

Reputation: 17444

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.

Upvotes: 0

Phil
Phil

Reputation: 815

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.

Upvotes: 2

Emil Eriksson
Emil Eriksson

Reputation:

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

Upvotes: 2

Uri
Uri

Reputation: 89729

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.

Upvotes: 11

Related Questions