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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/523767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:47:31  来源:igfitidea点击:

How to set background image in Java?

javaimagebackgroundset

提问by Dew

I am developing a simple platform game using Java using BlueJ as the IDE. Right now I have player/enemy sprites, platforms and other items in the game drawn using polygons and simple shapes. Eventually I hope to replace them with actual images.

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

For now I would like to know what is the simplest solution to setting an image (either URL or from local source) as the 'background' of my game window/canvas?

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

I would appreciate it if it isn't something long or complex as my programming skills aren't very good and I want to keep my program as simple as possible. Kindly provide example codes with comments to elaborate on their function, and also if it's in its own class, how to call on relevant methods used by it on other classes.

如果它不是很长或很复杂,我将不胜感激,因为我的编程技能不是很好,我想让我的程序尽可能简单。请提供带有注释的示例代码以详细说明它们的功能,以及如果它在自己的类中,如何调用它在其他类上使用的相关方法。

Thank you very much.

非常感谢。

采纳答案by coobird

The answer will vary slightly depending on whether the application or applet is using AWTor Swing.

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

(Basically, classes that start with Jsuch as JAppletand JFrameare Swing, and Appletand Frameare AWT.)

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

In either case, the basic steps would be:

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

  1. Draw or load an image into a Imageobject.
  2. Draw the background image in the painting event of the Componentyou want to draw the background in.
  1. 将图像绘制或加载到Image对象中。
  2. 在要绘制背景的绘画事件中绘制背景图像Component

Step 1.Loading the image can be either by using the Toolkitclass or by the ImageIOclass.

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

The Toolkit.createImagemethod can be used to load an Imagefrom a location specified in a String:

Toolkit.createImage方法可用于Image从 a 中指定的位置加载String

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");

Similarly, ImageIOcan be used:

同样,ImageIO可以使用:

Image img = ImageIO.read(new File("background.jpg");

Step 2.The painting method for the Componentthat should get the background will need to be overridden and paint the Imageonto the component.

步骤 2.Component应该获得背景的绘制方法需要被覆盖并将其绘制Image到组件上。

For AWT, the method to override is the paintmethod, and use the drawImagemethod of the Graphicsobject that is handed into the paintmethod:

对于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.
    // ....
}

For Swing, the method to override is the paintComponentmethod of the JComponent, and draw the Imageas with what was done in AWT.

对于 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.
    // ....
}

Simple Component Example

简单组件示例

Here's a Panelwhich loads an image file when instantiated, and draws that image on itself:

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

For more information on painting:

有关绘画的更多信息:

回答by coobird

Firstly create a new class that extends the WorldViewclass. I called my new class Background. So in this new class import all the Java packages you will need in order to override the paintBackgroundmethod. This should be:

首先创建一个扩展WorldView类的新类。我打电话给我的新班级Background。因此,在这个新类中,导入覆盖该paintBackground方法所需的所有 Java 包。这应该是:

import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;

Next after the class name make sure that it says extends WorldView. Something like this:

接下来在类名之后确保它说 extends WorldView。像这样的东西:

public class Background extends WorldView

Then declare the variables game of type Gameand an image variable of type Imagesomething like this:

然后声明类型为游戏的变量和类型Game为图像的变量,Image如下所示:

private Game game;
private Image image;

Then in the constructor of this class make sure the game of type Gameis in the signature of the constructor and that in the call to superyou will have to initialise the WorldView, initialise the game and initialise the image variables, something like this:

然后在这个类的构造函数中,确保游戏类型Game在构造函数的签名中,并且在对super你的调用中必须初始化WorldView,初始化游戏并初始化图像变量,如下所示:

super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();

Then you just override the paintBackgroundmethod in exactly the same way as you did when overriding the paintmethod in the Playerclass. Just like this:

然后,您只需以与覆盖类中的paintBackground方法时完全相同的方式覆盖该paint方法Player。像这样:

public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}

Now finally you have to declare a class level reference to the new class you just made in the Gameclass and initialise this in the Gameconstructor, something like this:

现在最后您必须声明对您刚刚在Game类中创建的新类的类级引用,并在Game构造函数中对其进行初始化,如下所示:

private Background image;

And in the Game constructor:
image = new Background(this);

Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable framehas been declared:

最后,您要做的就是将背景添加到框架中!这就是我确定我们都错过的事情。为此,您必须frame在声明变量后执行以下操作:

frame.add(image);

Make sure you add this code just before frame.pack();. Also make sure you use a background image that isn't too big!

确保在frame.pack();. 还要确保您使用的背景图片不要太大!

Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.

现在就是这样!我注意到游戏引擎可以处理 JPEG 和 PNG 图像格式,但也可以支持其他格式。尽管这有助于在您的游戏中包含背景图像,但它并不完美!因为一旦你进入下一个级别,你的所有平台和精灵都是不可见的,你只能看到你的背景图像和你在游戏中包含的任何 JLabels/Jbuttons。

回答by JavaIsCool

Or try this ;)

或者试试这个;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

回答by Ben Whithead

The Path is the only thing you really have to worry about if you are really new to Java. You need to drag your image into the main project file, and it will show up at the very bottom of the list.

如果您真的不熟悉 Java,那么 Path 是唯一真正需要担心的事情。您需要将图像拖到主项目文件中,它会显示在列表的最底部。

Then the file path is pretty straight forward. This code goes into the constructor for the class.

然后文件路径非常简单。此代码进入类的构造函数。

    img = Toolkit.getDefaultToolkit().createImage("/home/ben/workspace/CS2/Background.jpg");

CS2 is the name of my project, and everything before that is leading to the workspace.

CS2 是我的项目的名称,之前的所有内容都指向工作区。

回答by Joe McComas

<script>
function SetBack(dir) {
    document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>