Skip to main content
gamedev.net
🔒 Locked

[java] JComboBox issues

Started by ssdko2009 0 replies 850+ views
Original Post
ssdko2009
ssdko2009
Ok I'm changing my previous question to a much simpler one
For some odd reason I have a JComboBox actionDo all set up with a model. But when I try something like actionDo.setSelectedItem(myObject) it doesn't set it to that object. Yes it is uneditable, but myObject is one of the preexisting items that I can set actionDo to. If I want to to it the long hard way I can put in a for loop that runs thru actionDo's every item and compares it to myObject and if they are equal strings I just set actionDo's selected index to the index I compared. But really, why should I have to go thru all this?

Can anyone shed some light on this. I'm not very knowledgeable with ComboBox's in Java, but what I do know is that most sources say this should work.
Angex
Angex
Any chance you could post some code??

Just guessing here, but if "myObject" is a custom class, it could be todo with the equality

If you're using exactly the same objects as those in the list, there should be no problem.
Otherwise make sure you override "equals()" method.


Quick example, say we have the following (NB: I didn't override "equals()" in ComplexObject).



public class ComplexObject {

private int a,b;

public ComplexObject(final int a, final int <img src='http://public.gamedev.net/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' /> {
this.a = a;
this.b = b;
}

@Override
public String toString() {

return a + ", " + b;
}
}


// Elsewhere in code ...


ComplexObject a = new ComplexObject(10, 20);
ComplexObject b = new ComplexObject(100, 200);

ComplexObject c = new ComplexObject(100, 200); // Iam the same as "b".

ComplexObject [] list = {
a,
b
};

JComboBox box = new JComboBox( list );

box.setEditable(false);




If I try the following commands:



box.setSelectedItem( a ); // Works ok.
box.setSelectedItem( b ); // Works ok.

box.setSelectedItem( c ); // Does not work ok.



Even though objects b & c are "the same", the combo box won't accept object c

But if I modify the ComplexObject to include an equals() method:



public class ComplexObject {

@Override
public boolean equals(Object obj) {

if (obj == null) {
return false;
}

if (!(obj instanceof ComplexObject)) {
return false;
}

ComplexObject co = (ComplexObject) obj;

if (a != co.a) {
return false;
}

if (b != co.<img src='http://public.gamedev.net/public/style_emoticons/<#EMO_DIR#>/cool.gif' class='bbc_emoticon' alt='B)' /> {
return false;
}

return true;
}

}





// Elsewhere in code...

box.setSelectedItem( c ); // Now works <img src='http://public.gamedev.net/public/style_emoticons/<#EMO_DIR#>/smile.gif' class='bbc_emoticon' alt=':)' />

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.