在java中更改系统托盘图标
我只想更改应用程序的系统托盘图标图像。我做了两件事- 刚刚更改了默认程序中的URL-在java中更改系统托盘图标,java,image,swing,packaging,system-tray,Java,Image,Swing,Packaging,System Tray,我只想更改应用程序的系统托盘图标图像。我做了两件事- 刚刚更改了默认程序中的URL- final TrayIcon trayIcon = new TrayIcon(createImage("images/Graph.png", "tray icon")); 第二次尝试- Image img = Toolkit.getDefaultToolkit().getImage("images/Graph.png"); final TrayIcon trayIcon = new TrayIcon(img,
final TrayIcon trayIcon = new TrayIcon(createImage("images/Graph.png", "tray icon"));
第二次尝试-
Image img = Toolkit.getDefaultToolkit().getImage("images/Graph.png");
final TrayIcon trayIcon = new TrayIcon(img, "Application Name", popup);
在这两种情况下,应用程序都会启动,但不会显示任何图像。它是一个空白占位符。我做错了什么?
images/Graph.png
不是jar中图像的有效URL。因此,我猜第二次尝试时,img
是空的
我建议你这样做:
//Get the URL with method class.getResource("/path/to/image.png")
URL url = System.class.getResource("/images/Graph.png");
//Use it to get the image
Image img = Toolkit.getDefaultToolkit().getImage(url);
final TrayIcon trayIcon = new TrayIcon(img, "Application Name", popup);
您还应确保
图像/
位于类路径中。问题在于图像位于中时包含图像文件的方式。jar
,使用getResource()
或getresourceastream
,尝试以下操作:
try {
InputStream inputStream= ClassLoader.getSystemClassLoader().getResourceAsStream("/images/Graph.png");
//or getResourceAsStream("/images/Graph.png"); also returns inputstream
BufferedImage img = ImageIO.read(inputStream);
final TrayIcon trayIcon = new TrayIcon(img, "Application Name", popup);
}
catch (IOException e) {}
最初的计划有效吗?您只更改了图标的路径?原始程序中的灯泡工作正常。是的,我只是在第一次尝试时更改了图标的路径。当时您的路径似乎有问题。如果您正在使用灯泡示例,您应该能够更改图标并使其正常工作。丢失的文件?是否尝试其他文件类型?可能是这样吗?你不需要一个jar来为应用程序提供午餐,运行java someClass和java-jar someJar.jar的路径也不同。这可以工作,但不需要向类路径添加任何内容。但是为什么第一次尝试不起作用呢?@Dan这是路径的问题。您可以尝试
新建文件(“.”).getAbsolutePath()
以了解搜索图像时的当前目录。使用我给你的方法,你实际上给出了从类路径的根到图像的路径。这就是为什么即使图像在罐子里它也能工作的原因。