Reputation: 1469
I'm trying to add an icon to the system tray, however, when I run the application the icon is blank.
My project structure is like this:
root/
libs/
...
src/
com/
projname/
logic/
...
ui/
MyClass.java
...
res/
icon.png
I'm trying to add the icon inside MyClass.java, like so:
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);
}
I marked the res/ folder as Resources Root on IntelliJ, and I also built the .jar
to check if the icon was being added to it - and it is.
What am I doing wrong?
Upvotes: 1
Views: 593
Reputation: 1867
Most probably your image is larger than the tray icon size and gets cropped. That's why you see the icon as blank. So you have to set,
trayIcon.setImageAutoSize(true);
JavaDoc:
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.
Upvotes: 3