1

I am trying to write a retro snake game. I set a background image of an old Nokia, and I want to play the snake from its screen. However, I cannot put my gamepanel on my background image. Can I do that? I used this code for my background image.

Thanks.

JFrame frame = new JFrame("Retro Snake");
    frame.getContentPane().add(new GamePanel());
    try {
        frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Images\\background.jpg")))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    frame.setLocation(500, 100);
    frame.pack();
    frame.setVisible(true);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
jdyg
  • 711
  • 2
  • 8
  • 16
  • Rather than putting a `JPanel` on an image it is better to create a `JPanel` with custom painting. See ***[this](http://stackoverflow.com/questions/4051408/jpanel-with-image-background)*** link. – Extreme Coders Apr 29 '13 at 19:04
  • @ExtremeCoders: I see no problem with putting an image in an ImageIcon, in a JLabel and making the JLabel the contentPane and in fact I've done this without problem many times. What problems would you anticipate with this set up? – Hovercraft Full Of Eels Apr 29 '13 at 19:21
  • @HovercraftFullOfEels The problem is that if we want the image to scale itself according to the `JPanel's` size then it would not be possible with the above setup – Extreme Coders Apr 29 '13 at 19:25
  • @ExtremeCoders: OK, I will grant you that. – Hovercraft Full Of Eels Apr 29 '13 at 19:33

1 Answers1

3
  • Don't add the JPanel to a contentPane that you are only going to discard on the next line or two (as you're currently doing).
  • Give your new contentPane-JLabel a BorderLayout via setLayout(new BorderLayout())
  • add the gamepanel to the JLabel above, Borderlayout.CENTER.
  • Be sure that you make your gamepanel JPanel non-opaque by calling setOpaque(false) on it, so that the background JLabel shows its image.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373