简体   繁体   中英

JLabel from one panel link to another JPanel

I'm suppose to create a game using java app. I have a few JLabel with images in a JPanel and I would like to link these JLabels from a JPanel to different JPanel. Is it possible to do so? As in when the Jlabel is being clicked, another page will appear.

Thanks in advance.

Swing components can't be shared as they can only have a single parent.

However you can share the Icon of the label with another Swing component. So in your MouseListener you can use the getIcon() method of the label you clicked on. Then you can add the icon to another component is the second panel using the setIcon(...) method.

You have to be more specific. You need to include things like what technologies you're using. Is this a web based project? Is it a stand alone application? And what specifically you're trying to do. And "link" has too broad of a meaning. That could mean a lot of different things. You have to be more specific in order to get the proper help.

You can share the JLabel by making it a singleton like class.

public class SharedJLabel {
    private static JLabel imageLabel;
    static {
        //init the imageLabel here
    }

    public static JLabel getImageLabel() {
        return imageLabel;
    }
}

In your different JPanel classes, you can just use this class to use the shared JLabel:

SharedJLabel.getSharedImageLabel();

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