Search code examples
javaswingjcombobox

setSelectedItem method is not working


I am having problems with the setSelectedItem method of JComboBox. It is just not working.Here is my code; My Station and Division classes are ok. So they are not included. No matter what I try I am not able to set an item as selected in the ComboBox;

//ListItem Class

public class ListItem {
private String id;
private String value;

public ListItem()
{

    id = "";
    value = "";
}
public ListItem(String id, String value)
{

    this.id = id;
    this.value = value;

}

public String getID(){return this.id;}
public String getValue() { return this.value;}

public void setID(String id ){this.id = id;}
public void setValue(String value) {this.value = value;}
@Override
public String toString()
{
    return value;
}


//show station
private void showSelectedStation(String stationCode){


    stationDA = new StationDA();
    station = stationDA.getStationByCode(stationCode);

    //Assign values to Division fields
    jtxtStationCode.setText(Integer.toString(station.getStationCode()));
    jtxtStationName.setText(station.getStationName());


    divisionDA = new DivisionDA();
    division = divisionDA.getDivisionByCode(station.getDivisionCode());



    ListItem myItem = new ListItem(
    division.getDivisionCode(), division.getDivisionName());


    jcbDivisionName.setSelectedItem(myItem); //not working.Only the first Value in the     list is showing


}

Solution

  • ListItem myItem = new ListItem(
    division.getDivisionCode(), division.getDivisionName());
    jcbDivisionName.setSelectedItem(myItem); 
    

    You are using a custom Object. You need to implement the equals() method in order for the comboBox to select the correct item.