我正在尝试加载图片并设置为背景,但我在selectionPanel方法中收到错误“无法加载背景图片”。
似乎图像处理出了问题,但我无法找到答案。
public class selectionPanel extends JPanel
{
//Variable with the name of our pic
private static final String path = "selbkgrnd.jpg";
private ImageIcon imageIcon;
private Dimension windowSize;
private int imageHeight;
private int imageWidth;
protected selectionPanel()
{
this.imageIcon = new ImageIcon("selbkgrnd.jpg"); //Save image to imageIcon
Image image = this.imageIcon.getImage();
this.imageWidth = image.getWidth(null);
this.imageHeight = image.getHeight(null);
if ((this.imageWidth == -1) || (this.imageHeight == -1)) //Check if background image is succesfully loaded
{
JOptionPane.showMessageDialog(JOptionPane.getDesktopPaneForComponent(this), "Could not load background image", "Fatal error!", 0);
System.exit(-1);
}
this.windowSize = new Dimension(this.imageWidth, this.imageHeight);
}
protected void startScreen()
{
setOpaque(false);
setSize(this.windowSize);
}
protected int getImageHeight()
{
return imageHeight;
}
protected int getImageWidth()
{
return imageWidth;
}
@Override
public void paintComponent(Graphics g)
{
g.drawImage(this.imageIcon.getImage(), 0, 0, null);
super.paintComponent(g);
}
}
答案 0 :(得分:0)
通常这是因为您在查找图像文件的错误位置。尝试使用图像的完整路径,或者相对于用户目录的路径,可以找到:
System.out.println("user directory: " + System.getProperty("user.dir"));
修改强>
你说:
谢谢你使用完整路径,但如果它在源代码文件夹中,它不应该只使用图像名称吗?
没有。同样,Java将查找相对于用户目录的文件。
但请注意,如果图像位于类文件目录或相对于此目录的目录中,并且您创建了一个jar文件并需要访问图像,则无法使用文件。您需要将图像作为资源获取,相对路径将不同,因为它与user.dir无关,而是相对于类文件的位置。