熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java swing組件的串行化和讀取

2022-06-13   來源: Java核心技術 

  由於JButton和JTree都已經實現了Serializable接口因此Java swing組件的串行化和讀取是可以做到的
方法就是使用ObjectInputStream讀取文件中的對象使用ObjectOutputStream把對象寫入文件

  

  import javaioFileInputStream;
import javaioFileNotFoundException;
import javaioFileOutputStream;
import javaioIOException;
import javaioObjectInputStream;
import javaioObjectOutputStream;

  import javaxswingJButton;
import javaxswingJTree;

  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));
outForButtonwriteObject(button);
outForButtonclose();
ObjectOutputStream outForTree = new ObjectOutputStream(
new FileOutputStream(tree));
outForTreewriteObject(tree);
outForTreeclose();
} catch (FileNotFoundException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
// Read

  try {
ObjectInputStream inForButton = new ObjectInputStream(
new FileInputStream(button));
JButton buttonReaded = (JButton) inForButtonreadObject();

  ObjectInputStream inForTree = new ObjectInputStream(
new FileInputStream(tree));
JTree treeReaded = (JTree) inForTreereadObject();
} catch (FileNotFoundException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
} catch (ClassNotFoundException e) {
// TODO Autogenerated catch block
eprintStackTrace();
}

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25601.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.