Search code examples
javaswingjlabel

Displaying a JLabel on top of another JLabel


I have the following code:

try {
        File file_background = new File(
                "C:\\Users\\xxxx\\Desktop\\background.png");
        ImageIcon icon_background = new ImageIcon(
                ImageIO.read(file_background));
        JLabel background = new JLabel(icon_background);
        window.setContentPane(background);

        File file_car = new File(
                "C:\\Users\\xxxxxx\\Desktop\\car.png");
        ImageIcon icon_car = new ImageIcon(ImageIO.read(file_car));

        JLabel car = new JLabel(icon_car);
        car.setVisible(true);

        background.add(car);
        // TODO Get car showing on top of the background label

    } catch (IOException e) {

        e.printStackTrace();
    }

Where I'm attempting to have the car label show on TOP of the background label. But I'm only getting the background JLabel showing. I'm new to SWING so any suggestions to what steps I'm missing would be great.


Solution

  • ..I want to move it a later stage. But right now I want it to show first :)

    There are two ways,

    1st.

    • Put JLabel car to JPanel, drawing an Image by using paintComponent, instead of JLabel background (advantage JPanel is container with proper notifications for LayoutManager).

    • Put JLabel car to JLabel background, but JLabel haven't implemented any LayoutManager, have to set desired.

      1. Advantage all images in JLabel are static, with zero CPU and GPU inpact ad consumption in compare with paintComponent.
      2. Disadvantage JLabel isn't container and with proper notifications for LayoutManager, required a few code lones moreover in compare with JLabel placed in JPanel, for movement (AbsoluteLayout) is quite good solution.

    2nd.

    Draw both Images by using BufferedImage and Graphics.