Serializing swing/awt components

…衆ロ難τιáo~ 提交于 2019-12-20 06:20:09

问题


I am trying to serialize a JPanel but everytime i get this error:

java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: javax.swing.GroupLayout  

Can you tell me, what could be the problem or what is the proper way of serializing it.

What i do is pretty simple:

FOR Serializing:

FileOutputStream f = new FileOutputStream("myfile.dat");
ObjectOutputStream ostream = new ObjectOutputStream(f);
Object object = panel;  //where panel is a JPanel type object
ostream.writeObject(object);
ostream.close();

And now for deserializing:

File file = new File("myfile.dat");
ObjectInputStream in;
try {
   in = new ObjectInputStream(new FileInputStream(file));
   object = (JPanel) in.readObject();
   in.close();
} catch (Exception e2) {
   e2.printStackTrace();
}  

while reading the serialized object in last step i encounter the above error. What is the reason, or any idea how is should do this?


回答1:


JPanel implements Serializable...

But javax.swing.GroupLayout don't.

So, you need to change GroupLayout to another layout class!




回答2:


GroupLayout, which appears to have been added to the panel, is not serialisable. There are a few options (listed least to most favourable).

  • Subclass GroupLayout to create a serial proxy (see Effective Java 2nd Ed). This is a fair bit of work, and is complicated by GroupLayout not having a complete set of "getters and setters".

  • Replace GroupLayout with a serialisable LayoutManager. There's the functional but rough GridBagLayout in the Java library. Other layout managers are available.

  • Don't serialise the JPanel. Making AWT components serialisable (and the whole JavaBeans thing) was a laughable mistake.




回答3:


To serialize an object, all the objects it references need to also be serializable aswell. You can mark a reference transient if you don't want it to be serialized. This means, if your panel refers to objects which are not serilizable, make them serilizable aswell or mark them transient




回答4:


To be serializeable the object (and all the parts of it with exception of the POJOs) needs to implement the Serializable interface.

If you cannot change the class, take a look at XStream.



来源:https://stackoverflow.com/questions/9874304/serializing-swing-awt-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!