我正在使用Java构建一个桌游。 对于游戏板本身,我尝试将该板的图像放置为整个JPanel的背景,该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。此外,我在我的工作空间中的图片格式不正确。感谢帮助。
ImageIO.read(getClass().getResourceAsStream(resourcePath));
资源路径将相对于您的类文件而定。建议您在此网站上搜索相关问题,因为这已经被问过很多次了。 - Hovercraft Full Of Eels