Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to add objects to a JComboBox and assign a String to be shown?

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?

like image 814
Adrian Avatar asked Feb 15 '23 14:02

Adrian


1 Answers

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

like image 61
MadProgrammer Avatar answered Feb 17 '23 11:02

MadProgrammer