serialization and reading of Java swing components

Source: Internet
Author: User
Tags serialization

Since both JButton and JTree have implemented the serializable interface, the serialization and reading of the Java Swing components can be done.

The method is to use ObjectInputStream to read the objects in the file and write the object to the file using ObjectOutputStream.

Such as: import java.io.FileInputStream;
import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Javax.swing.JButton;
Import Javax.swing.JTree;  

public class Save {

public static void Main (string[] args) {

//Write
JButton button = new JButton ("TEST button");
JTree tree = new JTree ();
try {
ObjectOutputStream Outforbutton = new ObjectOutputStream (
New FileOutputStream ("button");
Outforbutton.writeobject (button);
Outforbutton.close ();
ObjectOutputStream outfortree = new ObjectOutputStream (
New FileOutputStream ("tree");
Outfortree.writeobject (tree);
Outfortree.close ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace (); }
//Read

try {
ObjectInputStream Inforbutton = new ObjectInputStream (
New FileInputStream ("button"));
JButton buttonreaded = (JButton) inforbutton.readobject ();

ObjectInputStream infortree = new ObjectInputStream (
New FileInputStream ("tree");
JTree treereaded = (jtree) infortree.readobject ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace (); } catch (ClassNotFoundException e) {
//TODO auto-generated catch block
E.printstacktrace ();
}

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.