0

I need to do a jet fighter game for my school project and I couldn't get how to put a plane image over a gif background. Here is what I try to do:

photo of what I am trying to do:

https://i.stack.imgur.com/ZWNFd.jpg

And here is the code I wrote so far:

public class GameScreen {
    
    public GameScreen() {
        JFrame frame=new JFrame();      
        JPanel panel=new JPanel();
        frame.setSize(500, 550);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        panel.setLayout(null);
        
        JLabel Background;
        Background=new JLabel(new ImageIcon(getClass().getResource("/image/background.gif")));
        Background.setBounds(0, 0, 500, 550);
        panel.add(Background);
        
        JLabel jet;
        jet=new JLabel(new ImageIcon(getClass().getResource("/image/jet.png")));
        jet.setBounds(400, 400, 50, 50);
        panel.add(jet);

        frame.setVisible(true);
    }
}

When I run this, the jet image does not show, because I think it stays below the background. How can I solve this issue?

camickr
  • 321,443
  • 19
  • 166
  • 288
Oğulcan
  • 17
  • 4
  • `background.gif` Is that an animated GIF? – Andrew Thompson Jan 03 '21 at 18:33
  • Yes, it is a gif. – Oğulcan Jan 03 '21 at 18:34
  • 1
    One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. The code in [this answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). *"Yes, it is a gif."* I didn't ask if it was a GIF, I asked if it was an **animated** GIF. – Andrew Thompson Jan 03 '21 at 18:35

1 Answers1

0
    JLabel Background;
    Background=new JLabel(new ImageIcon(getClass().getResource("/image/background.gif")));
    Background.setBounds(0, 0, 500, 550);
    panel.add(Background);
    
    JLabel jet;
    jet=new JLabel(new ImageIcon(getClass().getResource("/image/jet.png")));
    jet.setBounds(400, 400, 50, 50);
    panel.add(jet);

You are adding the labels to the same panel. Swing paints the last component added first. So the jet is painting and then the background is painted over top.

Swing is designed with a parent / child relationship.

  • frame
    • content pane
      • background
        • jet

The content pane of the frame is a JPanel, so there is no need for your extra "panel".

Instead your code should be something like:

jet.setSize( jet.getPreferredSize() );
jet.setLocation(...);
...

background.setLayout(null);
background.add(jet);
...

frame.add(background);

Now the components will be painted in the parent/child relationship.

camickr
  • 321,443
  • 19
  • 166
  • 288