System Tray icon looks distorted

Click Upvote picture Click Upvote · Sep 5, 2012 · Viewed 8.3k times · Source

I'm trying to have an icon be added and displayed to the system tray using Java. However the icon is always either too small, or its cut off in areas. Its the second one from left in case you couldn't tell.

What am I doing wrong here? How can I get this icon to be displayed fully? What's the standard icon size to be used for system tray?

Edit: I am using AWT SystemTray and TrayIcon

Answer

Redandwhite picture Redandwhite · Sep 5, 2012

After you've retrieved the actual image resource from disk, you can resize it to the size you need by creating a "fake" one on-the-fly and taking its width.

I found that this was better than using the setImageAutoSize(true) method, as that method does not scale the image smoothly at all.

BufferedImage trayIconImage = ImageIO.read(getClass().getResource("/path/to/icon.png"));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
TrayIcon trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH));