简体   繁体   中英

How to make JComponent Global

I create a JLabel in one Method and i would like to access it in my ItemListener. How can I make my JLabel "Public static"?

public class MainTicketPrinter implements ItemListener{

    public static void main(String[] args) {
        new MainTicketPrinter().ticket();
    }

    public void ticket() {
        JLabel lblTicket= new JLabel("This is a Ticket");
        lblTicket.addItemListener(this);      
    }
    public void itemStateChanged(ItemEvent e) {
        lblTicket.setVisible(true);
    }
}

This should work:

public class MainTicketPrinter implements ItemListener{
    public static JLabel lblTicket;

    public static void main(String[] args) {
        new MainTicketPrinter().ticket();
    }

    public void ticket() {
        lblTicket= new JLabel("This is a Ticket");
        lblTicket.addItemListener(this);    
    }

    public void itemStateChanged(ItemEvent e) {
        lblTicket.setVisible(true);
    }
}

edit: I'm not sure but perhaps it is possible to access the item throug the event that is called?

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