Java swing组件的串行化和读取

开发 后端
通过使用ObjectInputStream读取文件中的对象,使用ObjectOutputStream把对象写入文件,可实现Java swing组件的串行化和读取。

 

由于JButton和JTree都已经实现了Serializable接口,因此Java swing组件的串行化和读取是可以做到的。
方法就是使用ObjectInputStream读取文件中的对象,使用ObjectOutputStream把对象写入文件。

如:

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();
}

}

}


 

【编辑推荐】

  1. Java Swing开发中的线程安全
  2. Java Swing中键盘事件的处理
  3. 通过Java Swing看透MVC设计模式
  4. Java开发中的线程安全选择与Swing
责任编辑:仲衡 来源: 施小平个人博客
相关推荐

2009-07-10 09:38:06

Java swing组

2009-11-18 11:05:27

PHP串行化

2016-11-17 22:18:31

id串行化服务器

2009-09-11 12:17:59

C#控件属性

2009-11-02 16:41:55

VB.NET串行化对象

2019-03-25 07:39:35

ID串行化消息顺序性高可用

2010-01-12 10:29:51

VB.NET对象串行化

2010-01-06 10:49:54

PHP串行化JSON

2021-04-14 15:01:44

串行化方式缓存

2010-01-14 18:00:07

VB.NET串行化对象

2009-11-17 16:24:27

PHP变量串行化

2009-07-17 11:13:46

AWT和SwingSwing组件

2009-07-10 17:03:17

AWT组件Swing组件

2009-07-10 14:58:13

JLabel组件JFC和Swing

2010-01-06 10:58:06

建立JavaScrip

2012-01-17 13:16:34

JavaSwing

2009-07-15 11:02:32

Swing组件

2009-07-14 17:21:42

Swing组件

2009-07-10 16:29:32

Swing组件

2010-01-06 11:05:35

JSON
点赞
收藏

51CTO技术栈公众号