简体   繁体   中英

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. 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.

for example: I add this object to my tree:

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

And what I see on my GUI is:

package.workspace@1df38f3

I want alternative text instead of

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. If you can write a toString for your Workspace object then that will fix your problem. If you can't modify the Workspace object then you should create a wrapper object that has the toString you want.

Try to @Override the "toString()" method of your object that is in the ArrayList

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

...
}

Read about TreeCellRenderers and create your own one eg extend 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 ). The default implementation is to call toString but you can override it to generate any text you want. 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).

As any good book or tutorial on Java teaches you, Learn to override to java.lang.Object.toString()

Read the Java language API and it clearly states that all subclasses should override toString() . Doing so (in your case) makes these Objects ready to be passed (by reference value) to the code that sets the GUI text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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