Search code examples
javaswingjlabelimageicon

How to display a JLabel's icon over another JLabel's icon


Let's say I'm building a chess app with swing. I'm using an array of JLabels to represent the checkerboard (each has its appropriate icon set as a lightly/dark shaded box). I've created another array of JLabels to hold the icons of the chess pieces, but I'm not familiar enough with swing to know how to implement them to display on top of the checkerboard. Anyone know of any techniques?


Solution

  • I have written a small example that builds a window and two JLabels on top of each other.

    Note that the grey.jpg and pawn.png images have 128x128 size and the pawn one has transparent background (this way I prevent the background of the pawn image from hiding the grey rectangle box).

    Here is the ChessFrame class that builds the window and adds the components:

    import java.awt.BorderLayout;
    import java.awt.Color;
    
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    
    public class ChessFrame extends JFrame {
    
        private JPanel panel;
        private JLabel greyBox;
        private JLabel pawn;
    
    
        public ChessFrame() {
            super();
    
            /* configure the JFrame */
            this.setSize(300, 300);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
    
        public void addComponents() {
            panel = new JPanel();
            greyBox = new JLabel(new ImageIcon("images/grey.jpg"));
            pawn = new JLabel(new ImageIcon("images/pawn.png"));
    
            /* add the pawn inside the grey box (we have to set a layout for the grey box JLabel) */
            greyBox.setLayout(new BorderLayout());
            greyBox.add(pawn);
    
            /* add grey box to main JPanel and set its background to white so we observe the result better */
            panel.add(greyBox);
            panel.setBackground(Color.WHITE);
    
            this.getContentPane().add(panel);
        }
    
    
        @Override
        public void setVisible(boolean b) {
            super.setVisible(b);
        }
    
    }
    

    And here is a Main class that creates a ChessFrame object and shows the window:

    public class Main {
    
        public static void main(String[] args) {
            ChessFrame chessFrame = new ChessFrame();
    
            chessFrame.addComponents();
            chessFrame.setVisible(true);
        }
    
    }