Display a property of Objects in Jlist

只谈情不闲聊 提交于 2019-12-05 08:08:10

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