我设法将包含JTextArea和几个按钮的非常基本的GUI对象序列化为文件'test.ser'。恢复以前序列化的JFrame对象,怎么样?
现在,我想从'test.ser'中完全恢复先前保存的状态,但似乎对如何正确反序列化对象状态存在误解。
该类别MyFrame创建JFrame并对其进行序列化。
public class MyFrame extends JFrame implements ActionListener {
// Fields
JTextArea textArea;
String title;
static MyFrame gui = new MyFrame();
private static final long serialVersionUID = 1125762532137824262L;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
gui.run();
}
// parameterless default contructor
public MyFrame() {
}
// constructor with title
public MyFrame(String title) {
}
// creates Frame and its Layout
public void run() {
JFrame frame = new JFrame(title);
JPanel panel_01 = new JPanel();
JPanel panel_02 = new JPanel();
JTextArea textArea = new JTextArea(20, 22);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel_01.add(scrollPane);
// Buttons
JButton saveButton = new JButton("Save");
saveButton.addActionListener(this);
JButton loadButton = new JButton("Load");
loadButton.addActionListener(this);
panel_02.add(loadButton);
panel_02.add(saveButton);
// Layout
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, panel_01);
frame.getContentPane().add(BorderLayout.SOUTH, panel_02);
frame.setSize(300, 400);
frame.setVisible(true);
}
/*
*
*/
public void serialize() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
oos.writeObject(gui);
oos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ev) {
System.out.println("Action received!");
gui.serialize();
}
}
在这里,我尝试做反序列化:
public class Deserialize {
static Deserialize ds;
static MyFrame frame;
public static void main(String[] args) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
frame = (MyFrame) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
也许有人可以点我到哪里我的误解是方向?
你们会如何编写一个类,它将先前序列化的gui元素反序列化并恢复到以前的序列化状态?
我现在这样做的方式似乎有不止一个缺陷,对吧?
是的,我做到了。我有一个NullPointerException。我只是将代码更改为您现在看到的内容。没有错误消息了,但仍然没有得到反序列化。 – jottr 2010-04-26 08:54:51
我认为你需要展示框架。 – 2010-04-26 08:56:56
只是增加它INTIAL后 – jottr 2010-04-26 09:02:15