tags:

views:

30

answers:

2

I want to copy my private jlabel object to a new jlabel object and make the new one public. Idea is to allow anyone to access jlabel's properties but not to allow make any changes that will be displayed on the original interface. Below code doesnt work as it simply copies the reference of the original object.

public javax.swing.JLabel getCopyOfLabel(int labelno) {
    javax.swing.JLabel newlbl = new javax.swing.JLabel();
    if (labelno == 0) {
        newlbl = lbl_0_original;
        return newlbl;
    } else if (labelno == 1) {
        newlbl = lbl_1_original;
        return newlbl;
    } else {
        newlbl = lbl_2_original;
        return newlbl;
    }
}

How can I do it the way I want? Can I use clone() on this?

Thank You

+1  A: 

if JLabel's clone method is implemented you can use clone. Otherwise you'll have to replicate it (copy the properties of your private JLabel to your public JLabel). Then there is actually no use to the private JLabel and you can just instantiate a new JLabel in your if else. It's not a copier then but a factory (e.g MyJLabelFactory.getJLabel(labelNo) ))

Redlab
+1  A: 

if you use spring, you have utilities method for that ; see BeanUtils.copyProperties, for instance.

Istao