1

Is there any way that I can check if a system tray already exists? When I keep running the program to create a system tray then multiple occurrences appear, which means multiple programs are running. So, I need to check the system tray is already there?

davidxxx
  • 125,838
  • 23
  • 214
  • 215
H Athukorala
  • 739
  • 11
  • 32
  • 2
    What's a *system tray*? Also keep in mind that you need to add `System.exit(0);` at the end of main in some programs that do not auto terminate. – Aniket Sahrawat Mar 09 '18 at 07:59
  • I add my program details to the windows system tray. But when i go to another jFrame and come back to main jFrame another system tray will appear. – H Athukorala Mar 09 '18 at 08:03
  • 1
    Just to check you are talking about this: https://docs.oracle.com/javase/8/docs/api/java/awt/SystemTray.html so you have multiple application which can add to this systry ? – Saulius Next Mar 09 '18 at 08:12
  • 1
    Yes I have. But this is not working. I tried. – H Athukorala Mar 09 '18 at 08:33
  • Shell_NotifyIconGetRect() may help if you gave your icon a GUID. This is plain win32, but there must be a way in Java to invoke native functions. https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyicongetrect – Sahil Singh Apr 07 '20 at 20:30

1 Answers1

3

Check the tray content through multiple running applications

You cannot as SystemTray methods refer to the SystemTray of the current application.
So distinct applications don't share the same SystemTray state.

The SystemTray javadoc states indeed :

Every Java application has a single SystemTray instance that allows the app to interface with the system tray of the desktop while the app is running.

As a general way, multiple running JVMs should be isolated between them.
So your requirement should probably not be solved by coupling them.
If you run multiple times the same application, you should accept that each one has exactly the same behavior.
On the contrary, if you don't want to allow to run concurrently multiple times the same application, you could use a trick as opening a ServerSocket connection on a specific port at the application startup.

Check the tray content inside one running application

You can by using SystemTray.getTrayIcons() that returns the actual icons added to the tray by the application in a TrayIcon[] object.
You can so iterate on array elements and add the TrayIcon only if you found no match.

Additionally note that if you add twice the same TrayIcon instance, an IllegalArgumentException should be thrown according to the SystemTray.add() method :

else if (icons.contains(trayIcon)) {
    throw new IllegalArgumentException("adding TrayIcon that is already added");    
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215