I have a JComboBox that contains user defined objects that contain an equals() method. When I create the combo box I add a few objects, then I try to call setSelectedItem(aObject). This does not select the item. The text in the combo box is empty. When I click on it I can see that the item I tried to select is highlighted but it is not selected. My current workaround is to iterate through the items and find the index of the one I want to select. Then, I use setSelcetedIndex which works fine. Is this a Swing bug? Does anyone know why this might not work?
Wilfried LAURENT
Ranch Hand
Joined: Jul 13, 2001
Posts: 269
posted
0
Can you describe more explicitely your problem? I have tried it and it works fine : .... JComboBox combo = new JComboBox(); // The toString method of J returns the init argument J toto=new J("toto"); J titi=new J("titi" ); combo.addItem(titi); combo.addItem(toto); combo.setSelectedItem(toto); .... And I see "toto" in the text field of the combo. W.
[This message has been edited by Wilfried LAURENT (edited September 28, 2001).]
Matt Hansen
Ranch Hand
Joined: Jul 31, 2001
Posts: 34
posted
0
I do basically the same thing
I overrode the equals method so that it compares them by the string passed in to the constructor. That doesn't work. But this does:
Wilfried LAURENT
Ranch Hand
Joined: Jul 13, 2001
Posts: 269
posted
0
>object2 = new myObject("two"); >combo.setSelectedItem(new myObject("two")); No surprise here. object2 is a different object from new myObject("two"). These are two different references. So in the second line, you try to select an object that does not belong to the combo box. >I overrode the equals method so that it compares them by the >string passed in to the constructor. This should have worked. Did you override the equals method of the myObject class? Have a look at the JComboBox (probably in the ComboBoxModel) source code to see how this is done. It should help. W.
Wilfried LAURENT
Ranch Hand
Joined: Jul 13, 2001
Posts: 269
posted
0
>object2 = new myObject("two"); >combo.setSelectedItem(new myObject("two")); No surprise here. object2 is a different object from new myObject("two"). These are two different references. So in the second line, you try to select an object that does not belong to the combo box. >I overrode the equals method so that it compares them by the >string passed in to the constructor. This should have worked. Did you override the equals method of the myObject class? Have a look at the JComboBox (probably in the ComboBoxModel) source code to see how this is done. It should help. W.