如何在Java中设置背景图像?

Dew*_*Dew 22 java background image set

我正在使用BlueJ作为IDE开发一个使用Java的简单平台游戏.现在我在游戏中使用多边形和简单形状绘制玩家/敌人精灵,平台和其他物品.最终我希望用实际图像替换它们.

现在我想知道将图像(URL或本地源)设置为我的游戏窗口/画布的"背景"的最简单的解决方案是什么?

如果它不是很长或很复杂,我会很感激,因为我的编程技巧不是很好,我希望尽可能保持我的程序.请提供带有注释的示例代码以详细说明它们的功能,如果它在自己的类中,则如何调用它在其他类上使用的相关方法.

非常感谢你.

coo*_*ird 28

根据应用程序或小程序是使用AWT还是Swing,答案会略有不同.

(基本上,与启动类JJAppletJFrame是秋千,和AppletFrame是AWT).

无论哪种情况,基本步骤都是:

  1. 将图像绘制或加载到Image对象中.
  2. 在要绘制背景的绘画事件中绘制背景图像Component.

步骤1.加载图像可以使用Toolkit类或ImageIO类.

Toolkit.createImage方法可用于Image从以下位置指定的位置加载String:

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Run Code Online (Sandbox Code Playgroud)

同样,ImageIO可以使用:

Image img = ImageIO.read(new File("background.jpg");
Run Code Online (Sandbox Code Playgroud)

步骤2.Component需要覆盖背景的绘制方法,并将其绘制Image到组件上.

对于AWT,覆盖的paint方法是方法,并使用传递给drawImage方法的Graphics对象的paint方法:

public void paint(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}
Run Code Online (Sandbox Code Playgroud)

对于Swing,要覆盖的paintComponent方法是方法JComponent,并绘制Image与AWT中的内容相同的方法.

public void paintComponent(Graphics g)
{
????// Draw the previously loaded image to Component.
????g.drawImage(img, 0, 0, null);

????// Draw sprites, and other things.
????// ....
}
Run Code Online (Sandbox Code Playgroud)

简单组件示例

这是一个Panel在实例化时加载图像文件,并在自身上绘制图像:

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel()
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage("background.jpg");
    }

    public void paint(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关绘画的更多信息:

  • 不要忘记在绘制方法开始时调用 `super.paintXXX(g)`。 (2认同)