zach
zach

Reputation: 21

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?

Upvotes: 2

Views: 2630

Answers (5)

thejartender
thejartender

Reputation: 9379

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.

Upvotes: 0

StanislavL
StanislavL

Reputation: 57381

Read about TreeCellRenderers and create your own one e.g. 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

Upvotes: 2

gcooney
gcooney

Reputation: 1699

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

Upvotes: 1

Younes TARCHOUN
Younes TARCHOUN

Reputation: 131

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";
      }

...
}

Upvotes: 2

Pace
Pace

Reputation: 43817

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.

Upvotes: 2

Related Questions