(for those who haven’t been around here long, I periodically bitch about how some aspects of swing let the rest down by being crap API’s that greatly lower the average usefulness and quality of Swing. JTree is the very worst offender, followed by JTable).
This time it’s the otherwise rather respectable JComboBox. Ever wanted to react to things being added to your “isEditable() == true” JComboBox? Ever looked for the “getContents():Object[]” method and wondered why you can’t find it?
Ever looked at the so-called “model” for a JComboBox? It’s depressing. Obviously written by someone who either:
- had no idea what M/V/C means and couldn’t be bothered to find out
- was really really rushed for time and thought “heck, what’s a JComboBox between friends? No need for me to make this work with all the effort that [we]'ve put into making Swing M/V/C, I’ll just hack together some rubbish instead”.
So, in my own small way trying to make the world a better place, here’s a method that will do it for you. It’s simple and hacky. It’s also very silly that it’s not in the API already. I chose to return a List instead of the Object[] you might expect cos then you can do .contains() checks wihtout pain.
public List getContents( JComboBox box )
{
ArrayList contents = new ArrayList();
for( int i=0; i<box.getItemCount(); i++)
{
contents.add( box.getItemAt( i ) );
}
return contents;
}