Display property of objects in Jlist

I have an Ingredient class

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

multiple instances of this class are stored in the list of objects. I also have

 javax.swing.JList ListIng; 

A model is installed with it.

 ListIngModel = new DefaultListModel(); 

The idea is to use a Jlist to display the "NameP" field of all objects, select one of them for further inspection, and then capture the selected object:

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

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

+6
source share
1 answer

You must use JList CellRenderer

See How to use lists for more details.

In principle, this allows you to determine how the output object will look in the list model, as in the view. This method allows you to customize the view as needed, even replacing it at run time.

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; } } 
+5
source

All Articles