Question

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

Était-ce utile?

La solution

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));

Autres conseils

To display the icon at an optimal size, you will need to manually resize it to the correct size. This correct size can differ between operating systems and preferences, so Java provides a method to acquire the task bar icon dimensions, which are 16x16 in the case of your example image.

if (SystemTray.isSupported()) {
    SystemTray tray = SystemTray.getSystemTray();
    Dimension trayIconSize = tray.getTrayIconSize();
    // resize icon image to trayIconSize
    // create your tray icon off of the resized image
}

According to TrayIcon.setImageAutoSize(boolean).

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.

I've ended up combining some of these answers to make the code I'm using.

This is producing a good looking icon in my system tray from a png that starts at 100x100.

It's worth noting that on a retina MacBook the icon looks worse scaled down. So I do a check elsewhere to see if it's running on a mac and don't apply this if it is.

public Image imageForTray(SystemTray theTray){

    Image trayImage = Toolkit.getDefaultToolkit().getImage("my100x100icon.png");
    Dimension trayIconSize = theTray.getTrayIconSize();
    trayImage = trayImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH);

    return trayImage;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top