Tom Lilletveit
Tom Lilletveit

Reputation: 2002

Java: Creating copies of object in add method?

Is it possible in java when using the add command to create a copy of the object your adding?

I got this object:

JLabel seperator   = new JLabel (EMPTY_LABEL_TEXT);

That I add:

add (seperator,WEST);

if I want to add several objects of this type, I reckon I gotta make copies of them, is there a way of doing that in the add() method, and if not - what is the simplest way of creating copies of objects? I only need 3 of them, so I don´t want any loops

Upvotes: 0

Views: 150

Answers (3)

Udo Klimaschewski
Udo Klimaschewski

Reputation: 5325

Not directly in the add() method without any help. Swing components are serializable, so it should be fairly easy to write a helper method that copies a component using ObjectOutputStream and ObjectInputStream.

Edit: a quick example:

    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());
    }

Upvotes: 0

Alain BUFERNE
Alain BUFERNE

Reputation: 2071

I think Swing component generally don't implement Cloneable interface so You will be obliged to make yourself a copy or define your own MySeparator class that you will be using with add(new MySeparator());

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

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

is the best you can do. If the label has many different properties that you want to have on both copies, then use a method to create the three labels, to avoid repeating the same code 3 times:

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

Upvotes: 1

Related Questions