I want to add objects to a JComboBox but show a String on the JComboBox for each object.
For example, in the following html code
<select>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
in the first item, the String that is shown is "Item 1", but the value of the item is "1".
Is there a form to do something like that with a JComboBox?
Start by taking a look at How to Use Combo Boxes, in particular Providing a Custom Renderer
Basically, you want to define your object which will be contained within the combo box...
public class MyObject {
private String name;
private int value;
public MyObject(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
Then create a custom ListCellRenderer
that knows how to renderer it...
public class MyObjectListCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value instanceof MyObject) {
value = ((MyObject)value).getName();
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
}
Then populate you combo box and apply the cell renderer...
JComboBox box = new JComboBox();
box.addItem(new MyObject(..., ...));
//...
box.setRenderer(new MyObjectListCellRenderer());
You could, equally, override the toString
method of your object, but I tend to like to avoid this for display purposes, as I like the toString
method to provide diagnostic information about the object, but that's me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With