简体   繁体   English

将特定实例属性添加到JList

[英]Add specific instance attribute to a JList

Say we have the following array of instantiated objects: 假设我们有以下实例化的对象数组:

SomeClass[] items = {new SomeClass("Apples", 1.99f, 0.311f),
new SomeClass("Oranges", 0.99f, 0.396f),
new SomeClass("Bananas",2.99f,2.27f)};

Assume the constructor is String name, float price, float weight. 假设构造函数是String name,float price,float weight。

So now I create a JList and put it in a JScrollPane: 所以现在我创建一个JList并将其放在JScrollPane中:

itemsList = new JList(items);
ScrollPane itemsListScrollPane = new JScrollPane(itemsList);

Is there a way to override what's shows up in the scroll pane, so that only the name attribute shows up (and discard the other attributes) in it like so, without overriding the toString() method in the SomeClass class. 有没有办法覆盖滚动窗格中显示的内容,因此只有name属性在其中显示(并丢弃其他属性),而不会覆盖SomeClass类中的toString()方法。

Apples
Oranges
Bananas

I hope it's clear, if you have any questions I'll try to clarify. 我希望很清楚,如果你有任何问题我会尽力澄清。

Thanks. 谢谢。

Edit: I just want to clarify, is there a way to use for example a method written for SomeClass called getName() that returns the string value of the name attribute and let the JList display only that? 编辑:我只是想澄清,有没有办法使用例如为SomeClass编写的一个名为getName()的方法,它返回name属性的字符串值,让JList只显示?

You can set a ListCellRenderer on the JList, you can choose whatever you want to render anything. 您可以在JList上设置ListCellRenderer ,也可以选择任何要呈现的内容。 See also the official doc about JList 另请参阅有关JList的官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM