在java中读取图像时出现IllegalArgumentException

时间:2014-06-27 02:58:06

标签: java image swing jframe embedded-resource

我正在尝试将图像作为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();
    }

}

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

1 个答案:

答案 0 :(得分:0)

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