Java不加载嵌入的图像

时间:2012-12-24 17:51:55

标签: java embedded-resource

package common;

import java.awt.image.BufferedImage;
import java.io.InputStream;

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

public class ResourcesToAccess {
    public static Icon sharedAbstractDownIcon;
    public static Icon sharedAbstractPlayIcon;
    public static Icon sharedAbstractPauseIcon;
    public static Icon sharedAbstractBlackCursor;
    public static Icon sharedAbstractWhiteCursor;
    public ResourcesToAccess(){
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("/src/images/blackCursor.png");
        try{
            BufferedImage bi = ImageIO.read(is);
            sharedAbstractBlackCursor = (Icon) new ImageIcon(bi);
            new JFrame().add(new JLabel(sharedAbstractBlackCursor)).setVisible(true);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new ResourcesToAccess();
    }
}

我正在使用此代码来查看是否可以正确加载PNG图像以创建JLabel,图标等,但我收到的错误是:

java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at common.ResourcesToAccess.<init>(ResourcesToAccess.java:21)
    at common.ResourcesToAccess.main(ResourcesToAccess.java:29)  

为什么我会看到该错误消息?

1 个答案:

答案 0 :(得分:4)

尝试

this.getClass().getClassLoader().getResourceAsStream("images/blackCursor.png")

它正在查找你的类路径,因此不再有src目录