在Jlist中显示对象的属性 [英] Display a property of Objects in Jlist

查看:285
本文介绍了在Jlist中显示对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成分课

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;

模型设置为

ListIngModel = new DefaultListModel();

想法是使用Jlist显示所有对象的字段"NameP",选择其中一个要进一步检查,然后抓取所选对象:

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())

我可以在列表模型中加载对象,但是JList将显示这些对象的地址. 是否有一种优雅的方法可以使其显示所存储对象的属性?

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?

推荐答案

您应该使用JListCellRenderer

看看如何使用列表有关更多详细信息.

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.

例如

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

这篇关于在Jlist中显示对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆