0

我正在尝试创建显示联系人的列表,每个列表项在一行上显示姓名,在第二行上显示电话号码,也许还有图像或图标。我正在考虑为此使用两个标签,但我可以弄清楚如何使用自定义列表模型来实现这一点。

我的第一次尝试是在列表中添加一个包含我想要的信息的 Panel 对象,然后将其添加到默认列表模型的实例中,但这只会显示列表中的类名。

    DefaultListModel Clistmodel = new DefaultListModel();//
    Clistmodel.addElement(Contact);//Contact is an JPanel object
    GroupList.setModel(Clistmodel);//GroupList is the List object

这根本不起作用然后我了解到默认列表模型只知道如何呈现我认为的字符串,所以我必须创建一个自定义列表模型或自定义 ListCellRenderer,我真的不知道哪个会解决问题。

4

1 回答 1

5

Your question asks how to create a custom list model, however, that's not what you need (I don't think) as a DefaultListModel will work nicely for you. Rather you will need to work on the renderer. You need to create a non-GUI class to hold your information that each item will display, probably your Contact class, and then create a JList that holds this in its DefaultListModel.

The key for you will be to then create a custom list cell renderer to display the information on multiple lines -- perhaps a JTextArea, or a JPanel that holds two JLabels in a GridLayout. Please understand that the renderer does not display the actual underlying components, but something more akin to a stamped image of whatever components you're trying to display, so it will not have the full behaviors available to it as the actual component would. It will take work, but the writing a renderer section of the tutorial linked to by user714965 will show you how to do this.

Please give it a try, and then if you still are stuck, come on back with your code, your errors, and your questions, and we'll be better able to give you specific help.

于 2012-05-04T17:34:32.773 回答