0

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

3 Answers 3

1
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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

1 Comment

I added a quick example of how to clone a JComponent using the serialization feature of Swing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.