Link to home
Start Free TrialLog in
Avatar of Fengler
Fengler

asked on

saving (serializing) a complete tree structure of a JTree

Hello Experts,

how can I serialize (save to a file) a complete tree structure of a Jtree ?

I used DefaultMutableTreeNodes.

The complete Tree has about 8000 nodes.

First I read the node informations from a text file, but this takes about 10 minutes, which is too long.

So I am looking for a possibility to save the complete JTree object or the nodes.

Best regards

F
Avatar of chrisos
chrisos

JTree implements the Serialisable interface so you should be able to do the following:

File outFile = new File("wherever");
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myJTree);

To load the tree back in you do:

File inFile = new File("wherever");
FileInputStream fis = new FileInputStream(inFile);
ObjectInputStream ois = new ObjectInputStream(fis);
myJTree = (JTree)oos.readObject();

Hope that helps,

Chrisos



Ooo, Bad idea. You should never serialize Swing Objects, b/c they are not compatible with future versions. you should serialize the Tree Model instead.

Cheers,
Kylar
ASKER CERTIFIED SOLUTION
Avatar of Igor Bazarny
Igor Bazarny
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
the reason it is so slow is because each element likely has a reference to the tree, which causes a save of the whole tree for each element.

You should override the deafult serializer and walk the tree yourself, saving each node individually.

I had this same problem a few years back and eventually found this solution - went from 5 minutes to serialze a queue to 10 seconds, by serialing the queue myself and then serializing the ind objects
Avatar of sajuks
@bazarny..thanx a lot Sir..you really are a master:-)