开发者

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.ge开发者_高级运维t(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 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜