简体   繁体   中英

Java, Put a panel on the background image of frame

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);
  • 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.

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