Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

java - Item in JComboBox instance of an object

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should add to the JComboBox the Person objects, not just the name, so when you call Object item = event.getItem(); this will return the Person, not an String. If you want to display the person's name in the JComboBox, override the toString method in Person class to something like this:

public String toString()
    return this.naam;
}

And you should add the items to the list.

personenList.addItem(persoon);   

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...