Java app Tray Icon not displaying properly on CentOS

692 views Asked by At

I've written a Java app that can be used on both Windows and Linux. The app uses a TrayIcon. On Windows, this works perfectly, but on Linux (CentOS) the TrayIcon has 2 problems: 1) I've lost the transparency in my png image) and 2) the image looks like it is shifted up (more on this later).

I take into account the the different environments by getting the tray icon size and then scaling accordingly. Here is my code:

Dimension trayIconSize = tray.getTrayIconSize();
Image originalImage = toolkit.getImage("tray_icon.png");
Image scaledImage = originalImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH);
trayIcon = new TrayIcon(scaledImage, "Some Text");

On CentOS, the returned dimension for .getTrayIconSize() is 24x24, but after testing, it's actually fits a 24x32 (WxH) image, which accounts for the image appearing shifted up when it is set to 24x24.

Is there any way to maintain the background transparency? Also, any suggestions on getting a properly sized icon dynamically?

1

There are 1 answers

0
vlow On

Size

Although the documentation states that SystemTray.getTrayIconSize() "returns the size, in pixels, of the space that a tray icon will occupy in the system tray", the implementation actually returns a constant value depending on the operating system.

This is the actual implementation of the method in XSystemTrayPeer.java (Oracle JRE 1.8, OpenJDK is similar):

public Dimension getTrayIconSize() {
    return new Dimension(24, 24);
}

This is however not a Linux restriction. The Windows specific implementation returns a constant dimension of 16x16. But while most Windows systems actually seem to stick to that size, the vast multitude of Linux desktops also comes with an equally large variety of system trays in all shapes and sizes. The method is therefore error prone and cannot be relied on.

Transparency

Transparency is not supported in the X11 implementation of the system tray. See this answer and this bug report for details.

Alternatives

Take a look at dorkbox/SystemTray. It's an Apache 2.0 licensed tray lib which is also available through Maven/Gradle. It supports dynamic scaling and transparency on all platforms and also supports AppIndicator. I'm not affiliated with the project.