如何使用Java中的属性复制Swing组件?

时间:2018-04-30 13:10:44

标签: java swing

如何在保留其属性的同时复制Swing组件?我已经尝试使用clone()方法,但它失败并出现错误:

  

clone()在java.lang.Object

中具有受保护的访问权限

我应该如何使用代码复制Swing组件?

这是我目前的代码:

 public void copy_component() throws CloneNotSupportedException {

    Component[] components = design_panel.getComponents();

    for (int i = 0; i < components.length; i++) {

        boolean enable = components[i].isEnabled();

        if (enable == true) {

            JButton button = components[i].clone();
            design_panel.add(button);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

Cloneable已被破坏,不应该被使用 - 它的体系结构本质上是错误的,并且仅出于向后兼容的原因而存在。

这些天的常规方法是使用copy constructor,您可以在自己的对象上定义(或者有时定义一个实用方法来克隆单独的对象。)但是,如果你使用了很多不同的Swing组件会有点痛苦。

另一种方法是在对象中来回序列化对象,这样可以创建深度克隆对象。它只是一个黑客攻击,只有在对象为Serializable时才有效,但由于Swing组件符合此描述,您可以使用以下内容:

private Component cloneSwingComponent(Component c) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(c);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (Component) ois.readObject();
    } catch (IOException|ClassNotFoundException ex) {
        ex.printStackTrace();
        return null;
    }
}