Solved

saving (serializing) a complete tree structure of a JTree

Posted on 2001-06-06
5
1,906 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
HSSFWorkbook cannot be resolved error 10 50
servlet  URL Rewriting 1 27
egit plugin on eclipse 8 38
varialbe initialization 11 30
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

920 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now