我正在尝试从 Jar 文件加载图像。这是一行:
Image imgTrayIcon = new Image(display, this.getClass().getResourceAsStream("icon.ico"));
我见过很多使用此方法的示例,但是当我尝试这样做时,我收到错误提示说我的图像无效。这是堆栈跟踪:
[java] Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid image
[java] at org.eclipse.swt.SWT.error(SWT.java:4083)
[java] at org.eclipse.swt.SWT.error(SWT.java:3998)
[java] at org.eclipse.swt.SWT.error(SWT.java:3969)
[java] at org.eclipse.swt.internal.image.WinICOFileFormat.loadInfoHeader(WinICOFileFormat.java:200)
[java] at org.eclipse.swt.internal.image.WinICOFileFormat.loadIcon(WinICOFileFormat.java:127)
[java] at org.eclipse.swt.internal.image.WinICOFileFormat.loadFromByteStream(WinICOFileFormat.java:119)
[java] at org.eclipse.swt.internal.image.FileFormat.loadFromStream(FileFormat.java:48)
[java] at org.eclipse.swt.internal.image.FileFormat.load(FileFormat.java:84)
[java] at org.eclipse.swt.graphics.ImageLoader.load(ImageLoader.java:130)
[java] at org.eclipse.swt.graphics.ImageDataLoader.load(ImageDataLoader.java:22)
[java] at org.eclipse.swt.graphics.ImageData.<init>(ImageData.java:331)
[java] at org.eclipse.swt.graphics.Image.<init>(Image.java:545)
[java] at SysTray.run(Unknown Source)
我使用的图标绝对有效。我已经使用图标工具对此进行了检查。我也试过将图标放在与我的代码相同的目录中(不是 Jar-ing 它)并像这样使用它:
Image imgTrayIcon = new Image(display, "icon.ico");
这工作得很好,但是当我尝试将它放入 Jar 中时,却没有。我似乎无法弄清楚为什么会这样。我已经解压缩我的 Jar 以检查该文件是否已添加到 Jar 中并且它似乎在那里。我的 jar 没有任何复杂的文件夹结构。所有文件和资源都在同一层树中。
关于这里出了什么问题有什么想法吗?谢谢
下面是一些示例代码来重现该问题:
例子.java
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.*;
class Example {
public static void main(String[] args) {
Display display = Display.getDefault();
Image imgTrayIcon = new Image(display, Example.class.getClassLoader().getResourceAsStream("icon.ico"));
}
}
命令:
javac -cp "SWT.jar" Example.java
jar cf Example.jar *.class *.ico
java -cp "Example.jar;SWT.jar" Example
最佳答案
看起来您正在处理多线程应用程序。
从堆栈跟踪 Exception in thread "Thread-0"org.eclipse.swt.SWTException: Invalid image
看来您正在非 ui 线程中加载图像并尝试在一些 UI 元素。 See this .
在 UI 线程中,以下代码工作正常。 (图标文件在测试包
中)
package test;
import java.io.InputStream;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class IconTest
{
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setSize(200, 200);
shell.setLocation(20, 20);
InputStream stream = IconTest.class.getResourceAsStream("/test/icon.ico");
Image imgTrayIcon = new Image(display, stream);
shell.setImage(imgTrayIcon);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
if(imgTrayIcon != null)
imgTrayIcon.dispose();
display.dispose();
}
}
关于java - 无法从 Jar 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10896475/