简体   繁体   中英

Getting The Correct Position of an Item inside a JCombobox in Java

To get the position of an Item inside the combobox I typically use the getSelectedIndex() method, however this method no longer works when you have Items that are equal .

Example :

Suppose we have the following items in our JCombobox : {Harry , John , Mary , Harry} then when selecting Harry (the fourth item of the combobox) we do not get the correct output which should be: 3 but instead we get 0 (the position of the first Item).

The JCombobox implementation lets us add items that are equal but we still get this behaviour when we try to get their position inside the JCombobox using the getSelectedIndex() method.

So is there a way to get the correct position or index of an Item that is equal to another item in the JCombobox ?

Wrap the data within a custom class. You can override toString and return the data object for display by the JComboBox . For example:

public class MyClass{

    private String myName;

    public MyClass(String name){
        this.myName = name;
    }
    @Override
    public String toString(){
        return myName;
    }

}

myComboBox.add(new MyClass("Harry"));
myComboBox.add(new MyClass("John"));
myComboBox.add(new MyClass("Mary"));
myComboBox.add(new MyClass("Harry"));

The first and last objects will not be equal, according to their equals method - which leads to an important point: be sure the implementation of MyClass does not override equals , as this method is used by getSelectedIndex to get the index of the element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM