如何创建 ImageIcon 的实例
How to create an instance of ImageIcon
我正在尝试根据此处的说明创建 ImageIcon
的实例 (http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)
/** 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;
}
}
我的图像与 java class 在同一文件夹中,但它 returns "Couldn't find file: ....."。我该怎么办?
Class.getResource() 用于通过类加载器访问内容,例如东西和你的应用程序在同一个罐子里。
要从文件系统访问文件,请从文件创建 URL,例如new File(path).toURI().toURL();
我正在尝试根据此处的说明创建 ImageIcon
的实例 (http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)
/** 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;
}
}
我的图像与 java class 在同一文件夹中,但它 returns "Couldn't find file: ....."。我该怎么办?
Class.getResource() 用于通过类加载器访问内容,例如东西和你的应用程序在同一个罐子里。
要从文件系统访问文件,请从文件创建 URL,例如new File(path).toURI().toURL();