RahlSK RahlSK - 5 months ago 81
Java Question

jcombobox setSelectedItem

I have a created a combo box with three items. I am trying to set the selected item by index and value.


  1. When I do setSelectedIndex () the code works well.

  2. I am trying to set the selected item by value. So I try creating another object, with same value(variable name d), and do setSelectedItem but it fails. When I try printing out the selectedItem, it doesn't print 'C C'. It prints the previously selected item 'B B'



So how do set selectedItem by value? Do advice.
Thanks so much!

import javax.swing.JComboBox;

public class testt {

public static void main(String[] args) {

obj a = new obj("A A");
obj b = new obj("B B");
obj c = new obj("C C");

obj[] lst = { a, b, c };

JComboBox box = new JComboBox(lst);
box.setSelectedIndex(1);
System.out.println("value is:"+((obj) box.getSelectedItem()).toString());

obj d = new obj("C C");
box.setSelectedItem(d);
System.out.println(value is:"+((((obj) box.getSelectedItem()).toString());
}
}

class obj {
String value;
public obj(String value) {
this.value = value;
}
public String toString() {
return value;
}
}

Answer

Equals and Hashcode issue. The below should solve the problem.

  class obj {
    String value;    
    public obj(String value) {
        this.value = value;
    }    
    public String toString() {
        return value;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 17 * hash + Objects.hashCode(this.value);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final obj other = (obj) obj;
        if (!Objects.equals(this.value, other.value)) {
            return false;
        }
        return true;
    }
Comments