我已经设法将包含一个 JTextArea 和几个按钮的非常基本的 GUI 对象序列化到一个文件“test.ser”中。
现在,我想从“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 元素反序列化并恢复到它们先前序列化的状态?
我现在这样做的方式似乎在其概念上存在不止一个缺陷,对吧?