1

I created a TrayIcon via java. But I have a problem that if you run the runable jar file its creating again the same tray. Is there a way to disable it to open only one tray? Or to check if the tray already exist and by that not running the tray?

enter image description here

user5327287
  • 410
  • 4
  • 18
  • Possible duplicate of [Prevent launching multiple instances of a java application](https://stackoverflow.com/questions/7036108/prevent-launching-multiple-instances-of-a-java-application) – n00dl3 Apr 05 '18 at 14:05

1 Answers1

0

Runing multiple times the jar means starting multiple applications (and JVM) and every Java application has a single SystemTray instance.
From SystemTray javadoc :

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. T

So you should use a home strategy to detect if the application is already run or more simply prevent the application to run more than once.
Creating a server socket, bounds to a specific port (with a ServerSocket instance for example) as the application starts is a simple way to do that.
Here is an example with a exception thrown as detected :

public static void main(String[] args) {       
    assertNoOtherInstanceRunning();
    ...     // application code then        
}

public static void assertNoOtherInstanceRunning() {       
    new Thread(() -> {
        try {
            new ServerSocket(9000).accept();
        } catch (IOException e) {
          throw new RuntimeException("the application is probably already started", e);
        }
    }).start();       
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • ok thank you. I didn't know how to do it with the serversocket but now with your example I am. – user5327287 Apr 05 '18 at 14:18
  • Now after massing around with it, it still doesn't work. When I run the program on the theerd time it still executing it with no problem although I using the detection – user5327287 Apr 05 '18 at 14:47
  • @user5327287 My bad. Forget to `bind()` Note that the method blocks, so using a thread makes sense to not block the Main thread. – davidxxx Apr 05 '18 at 15:10