Skip to main content

JComboBox Convenience

1 reply [Last post]
mgrev
Offline
Joined: 2003-08-12
Points: 0

Conditionally adding items to a JComboBox is unnecessarily verbose. Today one need to iterate over the items to do this or cast the model to a DefaultComboBoxModel which isn't intuitional unless you read the API source code.

I suggest adding some or all of these convenience methods. They would make JComboBox easier to use.

</p>
<p>boolean addUniqeItem(Object item); /* Returns if item was added or not */</p>
<p>boolean setSelectItem(Object item, boolean addIfNotExist); /* Returns if item was added or not */</p>
<p>boolean containsItem(Object item);<br />

There are probably more.

Just my $02 on the path to newbie friendlyness.

Cheers,
Mikael Grev

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
jessewilson
Offline
Joined: 2003-06-14
Points: 0

I am the author of a free library called Glazed Lists. With this, you can use a List (like ArrayList) as your JComboBox model. Your problems are simplified because the List interface has a contains() method.

http://publicobject.com/glazedlists/

[code]EventList comboList = new BasicEventList();
EventComboBoxModel comboModel = new EventComboBoxModel(comboList);
JComboBox combo = new JComboBox(comboModel);

/* add unique */
Object o = ...
if(!comboList.contains(o)) comboList.add(o);

/* set selected */
Object m = ...
boolean addIfNotExist = ...
if(addIfNotExist && !comboList.contains(m)) comboList.add(m);
comboModel.setSelectedItem(m);[/code]

Cheers,
Jesse