javajtreetreemodel

Convert TreeModel.toString back to TreeModel


I am writing a java PlugIn for a robot, which involves using a dynamic JTree. When the program that uses the PlugIn is closed, and then reopened, any variables and object need to be stored in the robots DataModel. However, I cannot store a JTree in the programs data model, but I need to be able to store the tree so it can be changed and updated when the program is re-opened. So my question is, since i can store strings in the robots DataModel, is there a mechanic for converting the .toString of a JTree and its TreeModel, so that I can save the tree as a string, then convert it back when I reopen a program?

Thanks in advance.


Solution

  • DefaultTreeModel already implements Serializable. You don't need to use a String, just serialize the object to disk. Something like:

    FileOutputStream file = new FileOutputStream("treeModel.obj"); 
    ObjectOutputStream out = new ObjectOutputStream(file); 
    
    out.writeObject(treeModel); 
    out.close(); 
    file.close();