Solved

saving (serializing) a complete tree structure of a JTree

Posted on 2001-06-06
5
2,027 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

691 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