如何在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
How to set background image in Java?
提问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 J
such as JApplet
and JFrame
are Swing, and Applet
and Frame
are AWT.)
(基本上,与启动类J
如JApplet
和JFrame
是秋千,和Applet
和Frame
是AWT)。
In either case, the basic steps would be:
无论哪种情况,基本步骤都是:
- Draw or load an image into a
Image
object. - Draw the background image in the painting event of the
Component
you want to draw the background in.
- 将图像绘制或加载到
Image
对象中。 - 在要绘制背景的绘画事件中绘制背景图像
Component
。
Step 1.Loading the image can be either by using the Toolkit
class or by the ImageIO
class.
步骤 1.加载图像可以通过使用Toolkit
类或通过ImageIO
类。
The Toolkit.createImage
method can be used to load an Image
from a location specified in a String
:
该Toolkit.createImage
方法可用于Image
从 a 中指定的位置加载String
:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Similarly, ImageIO
can be used:
同样,ImageIO
可以使用:
Image img = ImageIO.read(new File("background.jpg");
Step 2.The painting method for the Component
that should get the background will need to be overridden and paint the Image
onto the component.
步骤 2.Component
应该获得背景的绘制方法需要被覆盖并将其绘制Image
到组件上。
For AWT, the method to override is the paint
method, and use the drawImage
method of the Graphics
object that is handed into the paint
method:
对于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 paintComponent
method of the JComponent
, and draw the Image
as 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 Panel
which 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:
有关绘画的更多信息:
- Painting in AWT and Swing
- Lesson: Performing Custom Paintingfrom The Java Tutorialsmay be of help.
- 在 AWT 和 Swing 中绘画
- 课程:从Java 教程执行自定义绘画可能会有所帮助。
回答by coobird
Firstly create a new class that extends the WorldView
class. I called my new class Background
. So in this new class import all the Java packages you will need in order to override the paintBackground
method. 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 Game
and an image variable of type Image
something like this:
然后声明类型为游戏的变量和类型Game
为图像的变量,Image
如下所示:
private Game game;
private Image image;
Then in the constructor of this class make sure the game of type Game
is in the signature of the constructor and that in the call to super
you 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 paintBackground
method in exactly the same way as you did when overriding the paint
method in the Player
class. 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 Game
class and initialise this in the Game
constructor, 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 frame
has 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>