[英]Accessing elements of an object in a jList/listModel
I'm trying to populate a jList, I want it to display a name but also store an ID (which is not displayed) for each item in the list. 我正在尝试填充jList,我希望它显示一个名称,但还要存储列表中每个项目的ID(未显示)。
I have created a list model and added each element as an object. 我创建了一个列表模型,并将每个元素添加为一个对象。 The object holds an int value (the ID) and a string value (the name): 该对象包含一个int值(ID)和一个字符串值(名称):
doorListModel.addElement(nextDoor);
Once all the elements have been added I then send this model to the jList: 添加完所有元素后,我将该模型发送到jList:
jList1.setModel(doorListModel);
When you run the program the jList appears to just show a memory location for each element: 当您运行程序时,jList似乎只是显示每个元素的存储位置:
How can I get the jList to just display the String value and, (assuming this is possible) how do I access the hidden int value if I was to select an item from the jList. 如果要从jList中选择一项,如何获取jList仅显示String值,以及(假设有可能)如何访问隐藏的int值。
Cheers. 干杯。
You've got two options as I see it: 在我看来,您有两种选择:
toString()
method since this is what the JList displays by default, or 您可以为Door类提供一个体面的toString()
方法,因为这是JList默认显示的内容,或者 toString()
result really shouldn't be used for production purposes but rather for debugging. 这是推荐的解决方案,因为toString()
结果实际上不应用于生产目的,而应用于调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.