Display a property of Objects in Jlist

Harter picture Harter · Feb 6, 2013 · Viewed 7.3k times · Source

I have a Ingredient class

public class Ingredient {
String NameP;
List ListS;
String Desc;
List ListT;
...

multiple instances of this class are stored in a Objects list. I have also a

javax.swing.JList ListIng;

With it's model set to

ListIngModel = new DefaultListModel();

The idea is to use the Jlist to display the field "NameP" of all objects, select one of them to be further inspected and then grab the selected object:

Ingredient Selected = ListIngModel.get(ListIng.getSelectedIndex())

I can load the objects in the list model, but then the JList displays the address of those. Is there an elegant way to make it display a property of the objects it stores?

Answer

MadProgrammer picture MadProgrammer · Feb 6, 2013

You should make use the JList's CellRenderer

Take a look at How to use Lists for more details.

Basically, it allows you to define what the give object in the list model will appear like in the view. This method allows you to customize the view as you need, even replacing it at run time.

For Example

public class IngredientListCellRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent(JList<?> list,
                                 Object value,
                                 int index,
                                 boolean isSelected,
                                 boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Ingredient) {
            Ingredient ingredient = (Ingredient)value;
            setText(ingredient.getName());
            setToolTipText(ingredient.getDescription());
            // setIcon(ingredient.getIcon());
        }
        return this;
    }
}