简体   繁体   中英

how to copy properties of a jlabel to another new jlabel

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

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 (eg MyJLabelFactory.getJLabel(labelNo) ))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM