Java:在添加方法中创建对象的副本



在使用add命令创建对象的副本时,在Java中是否有可能?

我得到了这个对象:

JLabel seperator   = new JLabel (EMPTY_LABEL_TEXT);

我添加:

add (seperator,WEST);

如果我想添加这种类型的几个对象,我认为我必须复制它们,是否有一种方法可以在add()方法中做到这一点,如果不是 - 如果没有 - 创建创建副本的最简单方法是什么对象?我只需要其中3个,所以我不想要任何循环

JLabel separator2 = new JLabel(EMPTY_LABEL_TEXT);
JLabel separator3 = new JLabel(EMPTY_LABEL_TEXT);

是您能做的最好的。如果标签具有您想要在这两个副本上具有许多不同的属性,请使用一种方法来创建这三个标签,以避免重复相同的代码3次:

JLabel separator = createLabelWithLotsOfProperties();
JLabel separator2 = createLabelWithLotsOfProperties();
JLabel separator3 = createLabelWithLotsOfProperties();

我认为摇摆组件通常不会实现 Cloneable接口,因此您将有义务使自己成为副本或定义您自己的MySeparator类,您将使用add(new MySeparator());

在没有任何帮助的情况下不直接在add()方法中。秋千组件是可序列化的,因此编写一个使用ObjectOutputStream和ObjectInputStream的组件的辅助方法应该很容易。

编辑:快速示例:

    public static JComponent cloneComponent(JComponent component) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(bos);
        oout.writeObject(component);
        oout.flush();
        ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        return (JComponent) oin.readObject();
    }
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        JLabel label1 = new JLabel("Label 1");
        JLabel label2 = (JLabel) cloneComponent(label1);
        label2.setText("Label 2");
        System.out.println(label1.getText());
        System.out.println(label2.getText());
    }

最新更新