程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java swing組件的串行化和讀取

Java swing組件的串行化和讀取

編輯:關於JAVA

由於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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved