Reputation: 1113
I have a JComboBox
with only one item. When I populate this item to the Box I immediately select it with combobox.setSelectedItem(item)
. But unfortunately I get -1 / null when I read the item with combobox.getSelectedIndex(0)
or combobox.getSelectedItem(item)
.
Sure I know which Item is in the box but I don't want to add a statement to react to that case.
Can you tell me how I can read the lone Item in the combobox?
Upvotes: 1
Views: 555
Reputation: 76426
Problem
combobox.setSelectedItem(item)
takes item
as an Object
and checks it among the items. Since combobox.getSelecedIndex
returns -1, we already know that there is no selection, therefore your selection was unsuccessful.
Reason
You passed an object to setSelectedItem
, but that Object
was not found among the items. It is easily possible that your Object
is a String
and you are passing a similar String
as a parameter, but the parameter you are passing is not the same String
, bug similar.
Behavior test
String foo = "bar";
boolean theSame = (foo == "bar"); //false
boolean similar = foo.equals("bar"); //true
Solution
Use the same Object
when you call setSelectedItem
instead of a similar Object
.
Upvotes: 3