序列化swing / awt组件 [英] Serializing swing/awt components
问题描述
我正在尝试序列化JPanel,但每次我都会收到此错误:
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.
我做的很简单:
FOR Serializing:
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();
现在进行反序列化:
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?
推荐答案
GroupLayout
,似乎已添加到面板中,不可序列化。有几个选项(列出最少至最优惠)。
GroupLayout
, which appears to have been added to the panel, is not serialisable. There are a few options (listed least to most favourable).
-
子类
GroupLayout
创建一个串行代理(参见Effective Java 2nd Ed)。这是一项相当多的工作,并且由于GroupLayout
没有一套完整的getter and setters而变得复杂。
Subclass
GroupLayout
to create a serial proxy (see Effective Java 2nd Ed). This is a fair bit of work, and is complicated byGroupLayout
not having a complete set of "getters and setters".
使用可序列化的 LayoutManager
替换 GroupLayout
。 Java库中有功能但粗略的 GridBagLayout
。其他布局管理器可用。
Replace GroupLayout
with a serialisable LayoutManager
. There's the functional but rough GridBagLayout
in the Java library. Other layout managers are available.
不要序列化 JPanel
。使AWT组件可序列化(以及整个JavaBeans的事情)是一个可笑的错误。
Don't serialise the JPanel
. Making AWT components serialisable (and the whole JavaBeans thing) was a laughable mistake.
这篇关于序列化swing / awt组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!