java向JPanel添加背景图像
我正在用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);
}
}
我读过使用ImageIcon是一个很好的修复方法,但我不知道如何正确使用它
编辑1-我在这里找到了我的答案 http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel 我的工作区中的图片格式也有问题。谢谢你的帮助
# 1 楼答案
getClass().getResource("/path/to/resource")
获取对资源的URL
引用,该引用可被ImageIO
用于读取资源因此,例如,如果图像位于Jar中的/images文件夹中,您可以使用
例如