简体   繁体   English

将对象保存在JTree中,但更改显示的名称(java swing)吗?

[英]Save objects in a JTree but change the displayed name (java swing)?

I have made a JTree and filled it with objects fron an ArrayList. 我做了一个JTree,并用ArrayList对象填充了它。 When I display the contents of the JTree with my GUI, I dont want to see the memory address wherethe object is stored, but a customized String. 当我使用GUI显示JTree的内容时,我不想看到存储对象的内存地址,而是看到了自定义的String。

for example: I add this object to my tree: 例如:我将此对象添加到我的树中:

DefaultMutableTreeNode tempnode = new DefaultMutableTreeNode(workspaces.get(i));

And what I see on my GUI is: 我在GUI上看到的是:

package.workspace@1df38f3 package.workspace@1df38f3

I want alternative text instead of 我想要替代文字而不是

package.workspace@1df38f3 package.workspace@1df38f3

To be displayed. 要显示。 How can I fix my code to support this? 如何修复我的代码以支持此功能?

JTree is going to call the toString function on the items you add and display that. JTree将在添加的项目上调用toString函数并显示它。 If you can write a toString for your Workspace object then that will fix your problem. 如果您可以为Workspace对象编写toString ,那么可以解决您的问题。 If you can't modify the Workspace object then you should create a wrapper object that has the toString you want. 如果无法修改Workspace对象,则应创建一个具有所需toString的包装对象。

Try to @Override the "toString()" method of your object that is in the ArrayList 尝试@Override ArrayList中对象的“ toString()”方法

class YourObject{
...
      @Override
      public String toString(){
           return "your string formatted here";
      }

...
}

Read about TreeCellRenderers and create your own one eg extend DefaultTreeCellRenderer. 阅读有关TreeCellRenderer的信息并创建自己的一个,例如扩展DefaultTreeCellRenderer。 In the method 在方法中

Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded,
                   boolean leaf, int row, boolean hasFocus)

Provide any desired logic 提供任何所需的逻辑

I'd recommend extending JTree and overriding convertValueToText( JTree javadoc ). 我建议扩展JTree并重写convertValueToText( JTree javadoc )。 The default implementation is to call toString but you can override it to generate any text you want. 默认实现是调用toString,但是您可以覆盖它以生成所需的任何文本。 No need to wrap all your array objects or override toString for display(I prefer to leave toString for debugging descriptions as opposed to for display text). 无需包装所有数组对象或覆盖toString进行显示(我更喜欢将toString留给调试描述,而不是显示文本)。

As any good book or tutorial on Java teaches you, Learn to override to java.lang.Object.toString() 正如任何有关Java的好书或教程所教您的,学习覆盖到java.lang.Object.toString()

Read the Java language API and it clearly states that all subclasses should override toString() . 阅读Java语言API,它明确指出所有子类都应重写toString() Doing so (in your case) makes these Objects ready to be passed (by reference value) to the code that sets the GUI text. 这样做(就您而言)使这些对象准备好(通过参考值)传递给设置GUI文本的代码。

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

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