如何在背景上放置图像?

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

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

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

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);
    }
}

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

mefy6pfw

mefy6pfw1#

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

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

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

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

frame.add(background);

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

相关问题