Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't getSelectedItem() on JComboBox generic?

JCombobox in Java 7 has been updated to use generics - I always thought it was a bit of an oversight that it didn't already so I was pleased to see this change.

However, when attempting to use JCombobox in this way, I realised that the methods I expected to use these generic types still just return Object.

Why on earth is this? It seems like a silly design decision to me. I realise the underlying ListModel has a generic getElementAt() method so I'll use that instead - but it's a bit of a roundabout way of doing something that appears like it could have been changed on JComboBox itself.

like image 278
Michael Berry Avatar asked Aug 11 '11 12:08

Michael Berry


People also ask

How do you check what is selected in a JComboBox?

You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.

Which method is used to add items to JComboBox?

Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items.

What is the difference between JComboBox and JList box give one method of each of them?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

How do I make JComboBox not editable?

u can make ur jcombobox uneditable by calling its setEnabled(false). A JComboBox is unEditable by default. You can make it editable with the setEditable(boolean) command. If you are talking about enabled or disabled you can set that by the setEnabled(boolean) method.


2 Answers

I suppose you refer to getSelectedItem()?

The reason is that if the combo box is editable, the selected item is not necessarily contained in the backing model and not constrained to the generic type. E.g. if you have an editable JComboBox<Integer> with the model [1, 2, 3], you can still type "foo" in the component and getSelectedItem() will return the String "foo" and not an object of type Integer.

If the combo box is not editable, you can always defer to cb.getItemAt(cb.getSelectedIndex()) to achieve type safety. If nothing is selected this will return null, which is the same behaviour as getSelectedItem().

like image 53
jarnbjo Avatar answered Oct 19 '22 03:10

jarnbjo


Here is a type-safe version:

public static <T> T getSelectedItem(JComboBox<T> comboBox) {     int index = comboBox.getSelectedIndex();     return comboBox.getItemAt(index); } 
like image 25
BullyWiiPlaza Avatar answered Oct 19 '22 05:10

BullyWiiPlaza