在java中获取自定义JPanel的深层副本
我有一个 JPanel,它是一个通用容器,它可以容纳各种组件并使用各种布局。
我的目的是制作此 JPanel 的深层副本,以便我可以调整复制的 JPanel 的大小或背景颜色,而不影响原始 JPanel 中的组件。
首先我尝试使用克隆方法,但我发现克隆只是复制顶层,JPanel 中的任何组件都是浅复制的,这意味着我只获得了原始组件的引用。 然后我看到一些文章说可以通过序列化 JPanel 来完成,但是当我这样做时出现以下错误:
java.io.NotSerializedException:sun.awt.windows.Win32OffScreenImage
有人知道吗?
谢谢, Sathish
更新::
这是获取深层复制的代码。
static public Object deepCopy(Object oldObj) throws Exception {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
return ois.readObject(); // G
} catch (Exception e) {
System.out.println("Exception in ObjectCloner = " + e);
throw (e);
} finally {
oos.close();
ois.close();
}
}
我传递的 JPanel 包含 2 个面板、jtable、2 个按钮。 但现在我得到 NullPointer 异常。 还有其他代码可以做到这一点吗?
I have an JPanel and it's a generic container, it could hold varied components and use varied Layout.
My purpose is to make a deep copy of this JPanel, so that i could resize or change the backgroud color of the copied one without impact on the components in the original JPanel.
First I tried to use Clone approach, but i found Clone just copy the top level, any components in the JPanel are shallow copied, that mean i just got references of origianl components.
and then i saw some articles said it can be done by serialization the JPanel, but I get following error when I do so:
java.io.NotSerializableException:sun.awt.windows.Win32OffScreenImage
Anyone have any idea?
Thanks,
Sathish
Update::
This is the code to get deep copy.
static public Object deepCopy(Object oldObj) throws Exception {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
return ois.readObject(); // G
} catch (Exception e) {
System.out.println("Exception in ObjectCloner = " + e);
throw (e);
} finally {
oos.close();
ois.close();
}
}
I am passing JPanel that contains 2panels,jtable,2buttons.
But now i get NullPointer Exception.
Is there any other code to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您收到错误的原因是图像不可序列化。您无法序列化图像,但您可以做的是将图像转换为数组,序列化它,然后恢复它并将其变回图像。这是一个例子:
这些方法将进入实现 Serialized 的类内部
The reason you are getting the error is because Image is not serializable. You cannot serialize an image, but what you can do is turn the image into an array, serialize it, then recover it and turn it back into an image. Heres an example:
these methods would go inside your class that implements Serializable