是否可以更改 Java Swing jList 中项目的*显示*名称?
我有一个使用 DefaultListModel 的 jList,并用从列表中获取的对象填充它(上下文:对象是 ABM 系统中的一种代理)。
是否可以更改 jList 中对象显示的名称?我没能找到任何关于这方面的东西......
I have a jList that uses DefaultListModel and I populate it with Objects I get from a list (context: the objects are a type of agent in ABM system).
Is it possible to change the name that is shown for the objects in the jList? I haven't been able to find anything on this...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要查看的信息(而不是 toString() 吐出的任何内容)包含在对象本身中,则实现此目的的最直接的“Swing”方法是通过使用 ListCellRenderer。将 ListCellRenderer(实际上是任何 CellRenderer)视为用于绘制列表中每个对象的橡皮图章。对象被传入,您设置组件,组件绘制您的对象,然后移动到下一个对象。 CellRenderer 从来没有任何状态。
考虑这个例子:
If the information you want to see (instead of whatever toString() spits out) is contained in the object itself, the most direct "Swing" way to accomplish this is through the use of a ListCellRenderer. Think of a ListCellRenderer (any CellRenderer really) as a rubber stamp used to draw each object in your list. The object is passed in, you setup the component, the component draws your object, and then moves on to the next object. The CellRenderer never has any state.
Consider this example:
我认为名称是由这些对象的 toString() 方法生成的。如果你能改变这一点,那是最简单的。否则,一种快速解决方案是在每个持有者对象周围包装某种持有者对象,该持有者对象为 JList 生成对象的视图,并且当您必须实际操作它时,您可以从中轻松检索所包含的对象。
扩展包装概念:
I think the names are produced by the
toString()
methods of those objects. If you can change that, that's easiest. Otherwise, a quick solution would be to wrap some kind of holder object around each one that generates the view of the object for the JList and from which you can retrieve the contained object easily enough when you have to manipulate it for real.To expand on the wrapper concept: