cr0mbly
cr0mbly

Reputation: 51

how to check if javafx application is already running programatically?

i'm trying to run a javafx application from a thread outside the scope of the application class. Th problem i'm using a while loop to generate the application and it throws an illegalstatexception whenever it is called twice, so i need a way to distinguish if the application is already running to continue with my other tasks, any ideas?

Upvotes: 1

Views: 2885

Answers (3)

Oleksandr Potomkin
Oleksandr Potomkin

Reputation: 339

public class MyServer implements Runnable{

    public static final int PORT = 99 ;

    private static ServerSocket serverSocket;

    private Window window;

    public MyServer(Stage window) throws AlreadyBoundException {

        if(serverSocket!=null && !serverSocket.isClosed())
            throw new AlreadyBoundException("The server is already running.");

        this.window = window;

        try( Socket clientSocket = new Socket("localhost", PORT);) {

            Platform.exit();

        } catch (IOException e) {

            final Thread thread = new Thread(this);

            thread.setDaemon(true);
            int priority = thread.getPriority();

            if(priority>Thread.MIN_PRIORITY)
                thread.setPriority(--priority);

            thread.start();
        }
 }

public void run() {

     try {
         serverSocket = new ServerSocket(PORT, 1);
         while (true) {
           Socket clientSocket = serverSocket.accept();
           clientSocket.close();

           Platform.runLater(()->window.requestFocus());
         }
     }catch (IOException e) {
         System.out.println("Error in MyServer: " + e);
     }
 }

}

And in the JavaFX APP:

@Override
public void start(Stage stage) throws Exception {

    // Start server
    new MyServer(stage);

    // ...

}

Upvotes: 1

Anubis  Lockward
Anubis Lockward

Reputation: 115

Based on @nejinx 's answer, you have to do this when calling Application.launch():

try {
    Application.launch(args);
} catch (IllegalStateException e) {}

That way, if the error happens, your program will just keep running and not try to start the application again.

Upvotes: 1

nejinx
nejinx

Reputation: 349

The only way you can do this is to catch the IllegalStateException

If you dig down into the JavaFX source code you see this:

if (launchCalled.getAndSet(true)) {
    throw new IllegalStateException("Application launch must not be called more than once");
}

Upvotes: 0

Related Questions