java 将背景图像添加到 JPanel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15711821/
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
Adding a background image to a JPanel
提问by Matthew G
I'm working on building a board game in Java. For the game board itself I was trying to place the image of the board as the background of the entire JPanel, which fills the JFrame. I found a way to do this, but only with the file stored locally, it needs to be able to take the image from the package the GUI is inside as well.
我正在用 Java 构建棋盘游戏。对于游戏板本身,我试图将板的图像作为整个 JPanel 的背景,填充 JFrame。我找到了一种方法来做到这一点,但只有使用本地存储的文件,它还需要能够从 GUI 所在的包中获取图像。
package Gui;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
//Proof of concept for setting an image as background of JPanel
public class JBackgroundPanel extends JPanel {
private BufferedImage img;
public JBackgroundPanel() {
// load the background image
try {
img = ImageIO.read(new File(
"C:\Users\Matthew\Desktop\5x5 Grid.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// paint the background image and scale it to fill the entire space
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
I've read that using ImageIcon is a good fix, but I don't know how to use it properly.
我读过使用 ImageIcon 是一个很好的解决方法,但我不知道如何正确使用它。
Edit 1 - I found my answer here http://www.coderanch.com/how-to/java/BackgroundImageOnJPanelI also had the picture formatted wrong in my workspace. Thanks for the help
编辑 1 - 我在这里找到了答案 http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel我的工作区中的图片格式也有误。谢谢您的帮助
采纳答案by MadProgrammer
- Make sure the resource you want to load is located within the Jar file
- Use
getClass().getResource("/path/to/resource")
to obtain aURL
reference to the resource, which can be used byImageIO
to read the resource
- 确保您要加载的资源位于 Jar 文件中
- 使用
getClass().getResource("/path/to/resource")
以获得URL
所述资源,其可以通过使用参考ImageIO
读取资源
So, for example, if the image was located in the /images folder inside your Jar, you could use
因此,例如,如果图像位于 Jar 内的 /images 文件夹中,则可以使用
ImageIO.read(getClass().getResource("/images/5x5 Grid.jpg"));
For example...
例如...