[英]Java Swing: how do I define how a JTree displays the “user object”?
When using a JTree
, a "user object" of a DefaultMutableTreeNode
can be set. 使用
JTree
,可以设置DefaultMutableTreeNode
的“用户对象”。 This can be of any kind, but to display it, its toString()
value is used. 这可以是任何类型,但要显示它,使用其
toString()
值。 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. 注意:我的用户对象必须与
String
不同,才能维护树和用户对象之间的映射。
I don't get what's your problem. 我不明白你的问题是什么。
The DefaultMutableTreeNode
will use the toString
method on the user object because it makes sense. DefaultMutableTreeNode
将在用户对象上使用toString
方法,因为它是有意义的。 The JTree
needs strings to draw objects so asking to your object its string rapresentation is ok. JTree
需要字符串来绘制对象,因此向对象询问其字符串表示是否正常。
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 own MutableTreeNode
: 如果你真的需要避免在你的对象上调用
toString
,你需要一种方法来提供它的字符串表示,但你必须编写自己的MutableTreeNode
:
class MyTreeNode implements MutableTreeNode
{
UserObject yourObject;
MyTreeNode(UserObject yourObject)
{
this.yourObject = yourObject;
}
// implement all needed methods to handle children and so on
public String toString()
{
// then you can avoid using toString
return yourObject.sringRapresentation();
}
}
But I really don't see the point of doing this.. in addition you can try extending the DefaultMutableTreeNode
by overriding toString
method, but you will need an additional reference to your object or some downcasts will be needed. 但我真的没有看到这样做的意义..此外你可以尝试通过覆盖
toString
方法来扩展DefaultMutableTreeNode
,但是你需要对你的对象进行额外的引用,或者需要一些向下转换 。
If you really need a different visualization than a string you will have to write your own rendered that implements TableCellRenderer
. 如果您确实需要与字符串不同的可视化,则必须编写自己的渲染来实现
TableCellRenderer
。
覆盖用户对象上的toString()或提供TreeCellRenderer , 基本示例
如果您只关心为用户对象显示的文本并且不想使用TreeCellRender,则另一种选择:扩展JTree并使用您自己的代码覆盖convertValueToText ,该代码为该对象创建描述性字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.