dreamz
dreamz

Reputation: 21

How to save and reload a JTree when running a program subsequent times?

We have written code for a JTree where we can add and remove nodes dynamically.

However, we cannot save the tree. Each time we run the program, we cannot get the previously created tree.

How can the JTree be saved and loaded?

Upvotes: 2

Views: 2539

Answers (1)

alain.janinm
alain.janinm

Reputation: 20065

You can Serialize/Deserialize your JTree, this is an example :

   JTree tree=new JTree();

   ....

   //serialization
    try{
        FileOutputStream file= new FileOutputStream("/home/alain/Bureau/serialisation.txt");
        ObjectOutputStream out = new ObjectOutputStream(file);
        out.writeObject(tree);
    }
    catch(Exception e){}
    //Deserialization
    JTree tree2=null;
    try{
        FileInputStream file= new FileInputStream("/home/alain/Bureau/serialisation.txt");
        ObjectInputStream in = new ObjectInputStream(file);
        tree2 = (JTree) in.readObject();
    }
    catch(Exception e){}

Note that transient fields are not Serializable so you should also serialize your TreeModel.

Upvotes: 2

Related Questions