java - 加载图像以设置背景时出错

标签 java image

我正在尝试加载图像并设置为背景,但我在选择面板方法中收到错误“无法加载背景图像”。

图像处理似乎出了问题,但我无法找出问题所在。

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);
  }
}

最佳答案

通常这是因为您在错误的位置查找图像文件。尝试使用图像的完整路径,或者是相对于用户目录的路径,可以通过以下方式找到该路径:

System.out.println("user directory: " + System.getProperty("user.dir"));

编辑
您声明:

Thank you it worked with the full path, but isnt it supposed to work with just the image name if it is inside the source code folder ?

没有。同样,Java 将查找相对于用户目录的文件。

但请注意,如果图像位于类文件目录或与此相关的目录中,并且您从中创建了一个 jar 文件并且需要访问图像,那么您将无法使用文件。您需要将图像作为资源获取,并且相对路径将不同,因为它不会与 user.dir 相关,而是相对于类文件的位置。

关于java - 加载图像以设置背景时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852959/

相关文章:

java - 如何更改 LibGdx 的复选框图像的大小?

jQuery 淡入/淡出图像背景故障

c - 如何将图像切片/切割成碎片

image - 这种裁剪算法更优雅的改写是什么? (在 Python 中)

PHP/JS - 即时创建缩略图或存储为文件

java - java中同时输入多个String数据

java - 正确的 XPath 但 sendKeys() 在 Selenium 中不起作用

java - 将多个对象添加到 ArrayList 会导致仅最后一个项目被多次添加

java - 将 JComponents 与 JPanel 的左侧和右侧对齐

ios - 调整图像选定区域的大小