系统托盘上的空白图标
Blank icon on system tray
我正在尝试将图标添加到系统托盘,但是,当我 运行 应用程序时,图标是空白的。
我的项目结构是这样的:
root/
libs/
...
src/
com/
projname/
logic/
...
ui/
MyClass.java
...
res/
icon.png
我正在尝试在 MyClass.java 中添加图标,如下所示:
private void addToSystemTray() throws AWTException {
if (!SystemTray.isSupported()) {
return;
}
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("icon.png"));
// construct tray icon
TrayIcon trayIcon = new TrayIcon(image, "My Project");
// add the tray image
tray.add(trayIcon);
}
我在 IntelliJ 上将 res/ 文件夹标记为 Resources Root,并且我还构建了 .jar
来检查图标是否被添加到它 - 它是。
我做错了什么?
您的图片很可能比托盘图标大,因此被裁剪了。这就是您看到该图标为空白的原因。所以你必须设置,
trayIcon.setImageAutoSize(true);
Java文档:
public void setImageAutoSize(boolean autosize)
Sets the auto-size property. Auto-size determines whether the tray
image is automatically sized to fit the space allocated for the image
on the tray. By default, the auto-size property is set to false.
If auto-size is false, and the image size doesn't match the tray icon
space, the image is painted as-is inside that space — if larger than
the allocated space, it will be cropped.
If auto-size is true, the image is stretched or shrunk to fit the tray
icon space.
我正在尝试将图标添加到系统托盘,但是,当我 运行 应用程序时,图标是空白的。
我的项目结构是这样的:
root/
libs/
...
src/
com/
projname/
logic/
...
ui/
MyClass.java
...
res/
icon.png
我正在尝试在 MyClass.java 中添加图标,如下所示:
private void addToSystemTray() throws AWTException {
if (!SystemTray.isSupported()) {
return;
}
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("icon.png"));
// construct tray icon
TrayIcon trayIcon = new TrayIcon(image, "My Project");
// add the tray image
tray.add(trayIcon);
}
我在 IntelliJ 上将 res/ 文件夹标记为 Resources Root,并且我还构建了 .jar
来检查图标是否被添加到它 - 它是。
我做错了什么?
您的图片很可能比托盘图标大,因此被裁剪了。这就是您看到该图标为空白的原因。所以你必须设置,
trayIcon.setImageAutoSize(true);
Java文档:
public void setImageAutoSize(boolean autosize)
Sets the auto-size property. Auto-size determines whether the tray image is automatically sized to fit the space allocated for the image on the tray. By default, the auto-size property is set to false.
If auto-size is false, and the image size doesn't match the tray icon space, the image is painted as-is inside that space — if larger than the allocated space, it will be cropped.
If auto-size is true, the image is stretched or shrunk to fit the tray icon space.