I want to add a JComboBox in Swing that is simple but I want to assign the values for each items in combo. I have the following code
JComboBox
Wrap your data in a simple class:
class MyData {
int value;
String text;
...
}
Now you can write your own renderer by extending BasicComboBoxRenderer. Cast the "value" to "MyData" and render the text.
public class Bla extends BasicComboBoxRenderer{
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if(value instanceof MyData) {
setText(((MyData) value).getText());
}
return super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
}
}
if you use Java7 it is best practice to use generics like @Taiki has shown. Now you can get the selected object by jc.getSelectedItem(). It is always from type MyData and you can access the text ("a", "b", etc.) and the value (1, 2, 3, etc.)