简体   繁体   中英

How to display a JLabel on top of another JLabel, with specified coordinate?

I'm working on a GUI for a Tic Tac Toe project, in which I want to get an image (the player's move) to show up when clicking the corresponding area. However, I can't figure out how to display a JLabel (the move) on top of another JLabel (the background).

I have searched and tried to use layeredpanes, but it just fails to show the entire frame when I run it. I am new to GUI, so I am not quite sure if I implemented it correctly.

layer = new JLayeredPane(); //set up the board as background String path = "sampleUrl"; URL url = new URL(path); BufferedImage image = ImageIO.read(url); bg4 = new JLabel(new ImageIcon(image)); layer.add(bg4, new Integer(-1)); frame.add(layer); frame.pack(); frame.addMouseListener(new MouseListener4()); String xPath = "sampleUrl"; URL xUrl = new URL(xPath); BufferedImage x = ImageIO.read(xUrl); icon = new JLabel(new ImageIcon(x)); layer.add(icon);

It just shows up a window with minimum width and height, without displaying the background. Is there something wrong with this code, or any other ways for me to put a JLabel on top of another JLabel?

You can add one label object into another, as JLabel is a container. Try something like this.

JLabel parentLabel = new JLabel("Parent");
JLabel childLabel = new JLabel("Child");
parentLabel.add(childLabel );

I highly recommend you to read about javafx if you are new in GUI.you can merge nodes in any way you need.you can put labels on each other using stackpane,and display them top and down of each other using gridpane very easily. more information on: https://docs.oracle.com/javafx/2/

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