Item in JComboBox instance of an object

2019-01-12 05:09发布

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?

2条回答
Viruses.
2楼-- · 2019-01-12 05:40

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

查看更多
戒情不戒烟
3楼-- · 2019-01-12 05:45

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 different JComboBox 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 override Person#toString() method only one time.

The way to go through is using a ListCellRenderer. Example:

public class Person {
    private String _name;
    private String _surname;

    public Person(String name, String surname){
        _name = name;
        _surname = surname;
    }

    public String getName() {
        return _name;
    }

    public String getSurname() {
        return _surname;
    }    
}

And here is the GUI:

import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Demo {

    private void initGUI(){
        Person person1 = new Person("First", "Person");
        Person person2 = new Person("Second", "Person");
        Person[] persons = new Person[]{person1, person2};

        /* 
         * This combo box will show only the person's name
         */
        JComboBox comboBox1 = new JComboBox(new DefaultComboBoxModel(persons));
        comboBox1.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if(value instanceof Person){
                    Person person = (Person) value;
                    setText(person.getName());
                }
                return this;
            }
        } );

        /* 
         * This combo box will show person's full name
         */
        JComboBox comboBox2 = new JComboBox(new DefaultComboBoxModel(persons));
        comboBox2.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if(value instanceof Person){
                    Person person = (Person) value;
                    StringBuilder sb = new StringBuilder();
                    sb.append(person.getSurname()).append(", ").append(person.getName());
                    setText(sb.toString());
                }
                return this;
            }
        } );

        JPanel content = new JPanel(new GridLayout(2, 2));
        content.add(new JLabel("Name:"));
        content.add(comboBox1);
        content.add(new JLabel("Surname, Name:"));
        content.add(comboBox2);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Demo().initGUI();
            }
        });

    }
}

If you run this example you'll see something like this:

enter image description here

As you can see both JComboBox contain Person objects but their representation is different in each one.

查看更多
登录 后发表回答