【问题标题】:IllegalArgumentException while reading an image in java在java中读取图像时出现IllegalArgumentException
【发布时间】:2014-08-18 01:22:48
【问题描述】:

我正在尝试获取图像作为 JFrame 窗口的图标,但在加载图像时出现此错误。

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at quest2.WindowFrame.<init>(WindowFrame.java:21)
    at quest2.WindowFrame.main(WindowFrame.java:39)

这是代码,但我删掉了与这个问题无关的几行。

import javax.imageio.ImageIO;  
import javax.swing.ImageIcon;
import javax.swing.JFrame;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class WindowFrame extends JFrame{

    private static BufferedImage BufImage;
    Image image;  //The image for the icon of the frame

    private static final long serialVersionUID = 1L;

    public WindowFrame() {

        //Get a Image for the Icon
            try {
            BufImage = ImageIO.read(getClass().getResource("/src/quest2/Logo.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        ImageIcon ii = new ImageIcon(BufImage);
        image = ii.getImage();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(720, 480);
        setTitle("Quest 2");
        setVisible(true);
        setResizable(false);
        setIconImage(image);
        setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        new WindowFrame();
    }

}

我不确定我做错了什么,所以如果有人可以帮我解决这个问题,那就太好了。

【问题讨论】:

  • 希望这个answer 能够在这个方向上为您提供一些帮助:-)

标签: java image swing jframe embedded-resource


【解决方案1】:

src 在运行时不会存在...

你应该使用...

getClass().getResource("/quest2/Logo.png")

改为

更新

您还应该注意图像可能是null 的情况,例如...

try {
    BufImage = ImageIO.read(getClass().getResource("/quest2/Logo.png"));
} catch (IOException e) {
    e.printStackTrace();
}

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(720, 480);
setTitle("Quest 2");
if (BufImage != null) {
    ImageIcon ii = new ImageIcon(BufImage);
    image = ii.getImage();
    setIconImage(image);
}
setLocationRelativeTo(null);
setVisible(true);

此外,更改框架的resizable 状态会影响其大小,您应该在设置框架大小之前执行此操作(最好使用pack)并最后调用setVisible

您可能还想查看Initial Threads 并确保在事件调度线程的上下文中初始化 UI

【讨论】:

  • 同时将图像设置代码移动到内部尝试对 BufImage 进行空检查可能是个好主意。
  • @JunedAhsan 或者至少处理BufImage 可能是null 的事实
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2016-08-13
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
相关资源
最近更新 更多