Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建ImageIcon的实例_Java_Swing_Imageicon - Fatal编程技术网

Java 如何创建ImageIcon的实例

Java 如何创建ImageIcon的实例,java,swing,imageicon,Java,Swing,Imageicon,我正在尝试根据此处的说明创建ImageIcon的实例() 我将该图像与java类放在同一文件夹中,但它返回“找不到文件:…”。我应该怎么做?

我正在尝试根据此处的说明创建
ImageIcon
的实例()

我将该图像与java类放在同一文件夹中,但它返回“找不到文件:…”。我应该怎么做?


要从文件系统访问文件,请从文件创建URL,例如
新文件(path).toURI().toul()

您甚至应该能够使用新的ImageIcon(路径,描述),如下所述:这是可行的,但对于Java程序来说,加载作为应用程序一部分的图标并不是正确的方法。Alda应该使用Class.getResource,尤其是当文件已经与类位于同一目录中时。
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                           String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}