java学习脚印: JTree序列化(Swing组件运用敏捷版)

java学习脚印: JTree序列化(Swing组件运用敏捷版)

写在前面

              JTree列属Swing中比较复杂一点的组件,相关知识点暂时没能整理出,现在给出一个JTree序列化的实例程序,以供参考。

JTree is a kind of complex swing component,here I simply give a example of serialization of JTree ,related knowledge will be update later.


1.运行效果(run screenshot)

Figure1  before saving to file



Figure 2   after loading from file




2.代码清单(code list)

package com.learningjava;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;

/**
 * This program demonstrate serializing a JTree.
 * Save left tree to file first ,then you can load it to right tree.
 * 
 * @author wangdq
 * 2013-12-25
 */
public class TreeSerializationDemo {
	  public static void main(String[] args) {
		 SwingUtilities.invokeLater(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				JFrame frame = new TreeSerializationFrame();
				frame.setLocationRelativeTo(null);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		 });
	  }
}
/**
 * Tree frame with two trees
 * left one is show at defualt with data
 * right one load from file
 * 
 * @author wangdq
 * 2013-12-25
 */
class TreeSerializationFrame extends JFrame {

	public TreeSerializationFrame() {
		
		super("Tree Serialization Demo");
		
		// Create a default left tree
	    leftTree = new JTree(initLeftTree());
	    JScrollPane scrollpaneLeft = new JScrollPane(leftTree);
	    
	    //create the right tree to read data and rebuild
	    rightTree = new JTree(new DefaultMutableTreeNode("Prepared for loading"));
	    JScrollPane scrollpaneRight = new JScrollPane(rightTree);
	    
	    //add to split pane
	    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
	    		scrollpaneLeft,scrollpaneRight);
	    this.add(splitPane,BorderLayout.CENTER);
	    
	    //add button panels
	    JPanel panel = new JPanel();
	    JButton btnSave = new JButton("Save Left Tree");
	    btnLoad = new JButton("Load To Right");
	    //save left tree
	    btnSave.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				saveLeftTree();
			}
	    });
	    //load right tree
	    btnLoad.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				loadToRightTree();
			}
	    });
	    panel.add(btnSave);
	    panel.add(btnLoad);
	    //default,disable load button
	    btnLoad.setEnabled(false);
	    this.add(panel,BorderLayout.NORTH);
	    this.setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
	}
	
	//save left tree to xml file
	private void saveLeftTree()  {
		try {
			String fileName = System.getProperty("user.home")
					+File.separator+"TreeSerial.xml";
			 XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream
					 (new FileOutputStream(fileName)));
			 encoder.writeObject(leftTree.getModel());
			 encoder.close();
			 //enable load button after saving the tree
			 btnLoad.setEnabled(true);
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	//load file and rebuild right tree
	private void loadToRightTree()  {
		try {
			String fileName = System.getProperty("user.home")
					+File.separator+"TreeSerial.xml";
			XMLDecoder decoder = new  XMLDecoder (new BufferedInputStream
					 (new FileInputStream(fileName)));
	        rightTree.setModel((TreeModel)decoder.readObject());
			decoder.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
    //init left tree
	private DefaultMutableTreeNode initLeftTree() {
	   
	   DefaultMutableTreeNode root = new DefaultMutableTreeNode("China");
	   //add one province
	   DefaultMutableTreeNode province = new DefaultMutableTreeNode("Guangdong");
	   root.add(province);
	   province.add(new DefaultMutableTreeNode("Guangzhou"));
	   province.add(new DefaultMutableTreeNode("Shenzhen"));
	   
       //add another province
	   province =new DefaultMutableTreeNode("Hubei");
	   root.add(province);
	   province.add(new DefaultMutableTreeNode("Wuhan"));
	   province.add(new DefaultMutableTreeNode("Huangshi"));
	   return root;
	}
	
	private static final long serialVersionUID = 1L;
	private final int DEFAULT_WIDTH = 300,DEFAULT_HEIGHT = 200;
	private JTree leftTree;
	private JTree rightTree;
	private JButton btnLoad;
}





当然你可以选择序列化到普通文本文件里,这里序列化到一个xml文件里了,保存在用户目录下。

Of course,you can save and read it in a normal text file,here we serialize it to a  xml file ,under the home directory.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值