Display a property of Objects in Jlist

梦想的初衷 提交于 2019-12-22 05:31:50

问题


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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/14740381/display-a-property-of-objects-in-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!