我正在使用 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 我的工作区中的图片格式也有误。感谢您的帮助
最佳答案
- 确保您要加载的资源位于 Jar 文件中
- 使用
getClass().getResource("/path/to/resource")
获取资源的URL
引用,可以被使用ImageIO
读取资源
因此,例如,如果图像位于 Jar 中的/images 文件夹中,您可以使用
ImageIO.read(getClass().getResource("/images/5x5 Grid.jpg"));
例如……
关于java - 将背景图像添加到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711821/