Solved

saving (serializing) a complete tree structure of a JTree

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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Should localization be done inside spring controller 5 37
Eclipse Java import and method not resolved 4 81
Html split(text) 2 31
Java List 4 41
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

733 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