3

我已经设法将包含一个 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 元素反序列化并恢复到它们先前序列化的状态?

我现在这样做的方式似乎在其概念上存在不止一个缺陷,对吧?

4

2 回答 2

1

发生什么了?你有例外吗?从代码的外观来看,ds从未初始化过。我相信,一旦反序列化,您将需要使用frame.setVisible(true);. 与往常一样,Swing(实际上是 AWT)应仅在 AWT 事件调度线程 (EDT) 上使用 - 使用java.awt.EventQueue.invokeLater.

通常使用静力学不是一个好主意。序列化 GUI 组件也不是。final很好,并且在大多数情况下会确保初始化实例和静态字段。

于 2010-04-26T08:53:08.713 回答
0

正如在每个 javadoc swing 组件中所说,序列化 JFrame 和其他 JFoo 的首选方法是XMLEncoder

经典的序列化适用于一些小的 GUI 应用程序,但不适用于长寿命的 GUI 组件应用程序。

于 2010-04-26T09:53:07.127 回答