简体   繁体   中英

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?

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 .

You can save your tree in a file and open it every time you re launch the application. You can also try to serialize and deserialize your tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM