Solved

saving (serializing) a complete tree structure of a JTree

Posted on 2001-06-06
5
1,947 Views
Last Modified: 2011-10-03
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
0
Comment
Question by:Fengler
5 Comments
 
LVL 3

Expert Comment

by:chrisos
ID: 6160059
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



0
 
LVL 4

Expert Comment

by:kylar
ID: 6160793
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
0
 
LVL 7

Accepted Solution

by:
Igor Bazarny earned 50 total points
ID: 6160863
Hi,

Here is the sample I made for someone at experts-exchange. It uses serialized model.


import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class TreeDemo{
    public static void main(String[] args){
        DefaultTreeModel model = null;

        final File serFile = new File("TreeDemo.ser");

        if( serFile.exists() ){
            try{
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFile));
                model = (DefaultTreeModel)ois.readObject();
                ois.close();
            }
            catch(IOException err){
                err.printStackTrace();
            }
            catch(ClassNotFoundException err){
                err.printStackTrace();
            }
        }

        if(model == null){
            model = new DefaultTreeModel(new DefaultMutableTreeNode("root"));
        }

        final DefaultTreeModel innerModel = model;

        JFrame frame = new JFrame("Tree Demo");
        final JTree tree = new JTree(model);
        tree.setEditable(true);
        final JTextField editor = new JTextField();
        final Runnable activateEditor = new Runnable(){
            public void run(){
                editor.requestFocus();
                editor.setSelectionStart(0);
                editor.setSelectionEnd(editor.getText().length());
            }
        };

        tree.setCellEditor(new DefaultCellEditor(editor));
        frame.getContentPane().add(new JScrollPane(tree));
        tree.registerKeyboardAction( new ActionListener(){
            public void actionPerformed(ActionEvent event){
                TreePath path = tree.getLeadSelectionPath();
                if( path == null ){
                    return;
                }
                Object last = path.getLastPathComponent();
                if( !(last instanceof DefaultMutableTreeNode) ){
                    return;
                }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)last;
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node");
                innerModel.insertNodeInto(newNode,node,node.getChildCount());
                TreePath newPath = path.pathByAddingChild(newNode);
                tree.makeVisible(newPath);
                tree.startEditingAtPath(newPath);
                SwingUtilities.invokeLater(activateEditor);
            }
        },"Add Item",KeyStroke.getKeyStroke(KeyEvent.VK_INSERT,0),JComponent.WHEN_FOCUSED);

        tree.registerKeyboardAction( new ActionListener(){
            public void actionPerformed(ActionEvent event){
                TreePath path = tree.getLeadSelectionPath();
                if( path == null ){
                    return;
                }
                Object last = path.getLastPathComponent();
                if( !(last instanceof DefaultMutableTreeNode) ){
                    return;
                }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)last;
                innerModel.removeNodeFromParent(node);
            }
        },"Delete Item",KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0),JComponent.WHEN_FOCUSED);

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter(){
            public void windowClosed(WindowEvent event){
                try{
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFile));
                    oos.writeObject(innerModel);
                    oos.close();
                }
                catch(IOException err){
                    err.printStackTrace();
                }
                System.exit(0);
            }
        });

        frame.pack();
        JButton modifyTest = new JButton("Modify Node");
        frame.getContentPane().add(modifyTest,BorderLayout.SOUTH);
        modifyTest.addActionListener( new ActionListener(){
            public void actionPerformed(ActionEvent event){
                TreePath path = tree.getLeadSelectionPath();
                Object last = path.getLastPathComponent();
                if( !(last instanceof DefaultMutableTreeNode) ){
                    return;
                }
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)last;
                node.setUserObject((String)node.getUserObject()+"WWWWWWWWWW");
                innerModel.nodeChanged(node);
            }
        });
        frame.setVisible(true);
    }
}

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
0
 
LVL 1

Expert Comment

by:jimsims
ID: 6178491
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
0
 
LVL 33

Expert Comment

by:sajuks
ID: 27290724
@bazarny..thanx a lot Sir..you really are a master:-)
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
GUI builder for Eclipse? 8 37
Java Loop 6 62
Error in @AspectJ Based AOP with Spring 2 14
runtime exception 2 30
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
The viewer will learn how to implement Singleton Design Pattern in Java.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question