Hello I have the following code to see if an item in the JComboBox is instance of a class(Persoon).
public class ItemChangeListener implements ItemListener {
Persoon selectedPerson;
RekeningApp app;
PersoonView view;
public ItemChangeListener(PersoonView view) {
this.view = view;
}
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
System.out.println("Itemchangelistener " + item);
// do something with object
if(item instanceof Persoon) {
System.out.println("Instance");
this.selectedPerson = (Persoon) item;
view.setOverzicht(this.selectedPerson);
} else {
this.selectedPerson = null;
}
}
}
}
The output of item is the value of persoon.name variable. so the items in the JComboBox are actually strings.
this is how the JComboBox list is set.
personenList.addItem(persoon.getNaam());
My question is.. how can I check If this Persoon object excists and is the same as in the JComboBox?
You should add to the
JComboBox
thePerson
objects, not just the name, so when you callObject item = event.getItem();
this will return thePerson
, not anString
. If you want to display the person's name in theJComboBox
, override thetoString
method inPerson
class to something like this:And you should add the items to the list.
Edit
If you don't want (or can) override the
toString
method you should use a custom renderer. This is a link to and example:http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer
Override
toString
method just for display purposes isn't a good practice. Also it's a potential bottleneck. Lets say for example you need to show two differentJComboBox
with persons: in one of them you need to show only the name and in the other one you need to show fullname. You can overridePerson#toString()
method only one time.The way to go through is using a ListCellRenderer. Example:
And here is the GUI:
If you run this example you'll see something like this:
As you can see both
JComboBox
containPerson
objects but their representation is different in each one.