如何在背景上放置图像?

evrscar2  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(408)

我需要为我的学校项目做一个喷气式战斗机游戏,但我不知道如何在gif背景上放置飞机图像。以下是我尝试做的:
我正在尝试做的事情的照片:

这是我迄今为止写的代码:

  1. public class GameScreen {
  2. public GameScreen() {
  3. JFrame frame=new JFrame();
  4. JPanel panel=new JPanel();
  5. frame.setSize(500, 550);
  6. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  7. frame.getContentPane().add(panel);
  8. panel.setLayout(null);
  9. JLabel Background;
  10. Background=new JLabel(new ImageIcon(getClass().getResource("/image/background.gif")));
  11. Background.setBounds(0, 0, 500, 550);
  12. panel.add(Background);
  13. JLabel jet;
  14. jet=new JLabel(new ImageIcon(getClass().getResource("/image/jet.png")));
  15. jet.setBounds(400, 400, 50, 50);
  16. panel.add(jet);
  17. frame.setVisible(true);
  18. }
  19. }

当我运行这个,喷气机图像不会显示,因为我认为它停留在背景之下。如何解决这个问题?

mefy6pfw

mefy6pfw1#

  1. JLabel Background;
  2. Background=new JLabel(new ImageIcon(getClass().getResource("/image/background.gif")));
  3. Background.setBounds(0, 0, 500, 550);
  4. panel.add(Background);
  5. JLabel jet;
  6. jet=new JLabel(new ImageIcon(getClass().getResource("/image/jet.png")));
  7. jet.setBounds(400, 400, 50, 50);
  8. panel.add(jet);

将标签添加到同一面板。swing绘制首先添加的最后一个组件。所以喷气式飞机在作画,然后背景画在上面。
swing是用父/子关系设计的。
框架
内容窗格
背景
喷气式飞机
框架的内容窗格是一个jpanel,因此不需要额外的“panel”。
相反,您的代码应该是这样的:

  1. jet.setSize( jet.getPreferredSize() );
  2. jet.setLocation(...);
  3. ...
  4. background.setLayout(null);
  5. background.add(jet);
  6. ...
  7. frame.add(background);

现在将在父/子关系中绘制组件。

展开查看全部

相关问题