Domanda

Okay, I'm very new to Java so please bear with me.

I am using Netbeans 6.8 to write a small desktop application that includes a JTree component, and my requirement is that I be able to save and load the tree structure, but that the structure allows for three items of information per tree node - The text to be displayed as the node, a unique identifier, and a file name.

Of course I would also need to be able to get all three bits of information when a node is clicked.

I have successfully saved the and loaded the tree model using getModel() and XMLDecoder/encoder, but this of course only saves the default tree model.

I have followed several tutorials on creating a custom tree model but I have found them confusing, and I have been unable to transfer what they were telling me into my own project, since of course they usually create an entire example application in one go.

Assuming that a tree model like this is even possible please could someone explain how to go about creating such a model, and most importantly, how to place the model into a JTree that already exists in the application (and how I would go about retrieving the information when a node is clicked - I can currently find the selected node and retrieve its text)

If this is not possible Id gladly hear any alternative methods that result in the same functionality.

A solution has been reached so thanks to everyone for their efforts, however the correct answer must go to Andrew for posting it first!

For those interested: I used the Netbeans IDE to create a new Javabean object. Once I realised the difference between this and a normal object I managed to place a newly created Javabean object into a tree node. Just to make it all good, my original method of saving still works fine!

thanks for your efforts everyone.

MVK

È stato utile?

Soluzione

The text to be displayed as the node, a unique identifier, and a file name.

Encapsualte them in a JavaBean Object and use an appropriate renderer.

Altri suggerimenti

By default, JTree uses a DefaultTreeModel which in turn uses a DefaultMutableTreeNode to represent each node. You can assign any object to a node, and it will be rendered by calling it's toString() method.

So, the simplest solution is to encapsulate all the data you need in an class and implement the toString() method to return whatever you want to be displayed. As an added bonus, if you implement your class following the JavaBeans spec, you get XML serialization for free.

You really should take a look at the Swing tutorial, specifically How to use Trees. Models, renderers and editosr will be more clear after you read how to handle trees, list and tables.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top