Java Swing:如何定义 JTree 如何显示“用户对象”?
使用JTree
时,可以设置DefaultMutableTreeNode
的“用户对象”。它可以是任何类型,但要显示它,需要使用其 toString()
值。这不是我需要的。
如何更改用户对象的显示方式?
注意:我的用户对象必须与String
不同才能维护树和用户对象之间的映射。
When using a JTree
, a "user object" of a DefaultMutableTreeNode
can be set. This can be of any kind, but to display it, its toString()
value is used. This is not what I need.
How can I change the way a user object is displayed?
NOTE: My user object has to be something different than a String
to be able to maintain mapping between the tree and the user objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白你有什么问题。
DefaultMutableTreeNode
将在用户对象上使用toString
方法,因为它有意义。 JTree 需要字符串来绘制对象,因此向您的对象询问其字符串表示形式就可以了。如果您确实需要避免在对象上调用
toString
,您将需要一种方法来提供它的字符串表示形式,但您必须编写自己的MutableTreeNode
:但是我真的不明白这样做的意义..此外,您可以尝试通过覆盖
toString
方法来扩展DefaultMutableTreeNode
,但是您将需要对对象的额外引用或者需要一些沮丧。如果您确实需要与字符串不同的可视化效果,则必须编写自己的实现
TableCellRenderer
的渲染。I don't get what's your problem.
The
DefaultMutableTreeNode
will use thetoString
method on the user object because it makes sense. TheJTree
needs strings to draw objects so asking to your object its string rapresentation is ok.If you really need to avoid calling
toString
on your object you will need a way to provide a string rapresentation of it anyway, but you will have to write your ownMutableTreeNode
:But I really don't see the point of doing this.. in addition you can try extending the
DefaultMutableTreeNode
by overridingtoString
method, but you will need an additional reference to your object or some downcasts will be needed.If you really need a different visualization than a string you will have to write your own rendered that implements
TableCellRenderer
.重写用户对象上的 toString() 或提供 TreeCellRenderer,基本示例
Override toString() on your user object OR provide a TreeCellRenderer, basic example
如果您只关心为用户对象显示的文本并且不想打扰 TreeCellRender,则还有另一种选择:扩展 JTree 并覆盖 convertValueToText 使用您自己的代码为该对象创建一个描述性字符串。
Another alternative if you just care about the text shown for the user object and don't want to bother with TreeCellRender: extend JTree and override convertValueToText with your own code that creates a descriptive string for that object.