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