简体   繁体   English

JLabel从一个面板链接到另一个JPanel

[英]JLabel from one panel link to another JPanel

I'm suppose to create a game using java app. 我想使用Java应用程序创建游戏。 I have a few JLabel with images in a JPanel and I would like to link these JLabels from a JPanel to different JPanel. 我在JPanel中有一些带有图像的JLabel,我想将这些JLabel从一个JPanel链接到另一个JPanel。 Is it possible to do so? 有可能这样做吗? As in when the Jlabel is being clicked, another page will appear. 与单击Jlabel时一样,将显示另一个页面。

Thanks in advance. 提前致谢。

Swing components can't be shared as they can only have a single parent. Swing组件只能共享一个父级,因此无法共享。

However you can share the Icon of the label with another Swing component. 但是,您可以与另一个Swing组件共享标签的图标。 So in your MouseListener you can use the getIcon() method of the label you clicked on. 因此,在MouseListener中,您可以使用单击的标签的getIcon()方法。 Then you can add the icon to another component is the second panel using the setIcon(...) method. 然后,您可以使用setIcon(...)方法将图标添加到第二个面板的另一个组件中。

You have to be more specific. 您必须更具体。 You need to include things like what technologies you're using. 您需要包括诸如所使用的技术之类的内容。 Is this a web based project? 这是一个基于Web的项目吗? 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. 您可以通过将JLabel设置为单例类来共享它。

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: 在不同的JPanel类中,您可以使用此类来使用共享的JLabel:

SharedJLabel.getSharedImageLabel();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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