如何检查javafx应用程序是否已经以编程方式运行?

时间:2014-07-27 02:04:20

标签: java javafx

我正在尝试从应用程序类范围之外的线程运行javafx应用程序。问题我正在使用while循环来生成应用程序,并且每次调用它时都会抛出非法的statexception,所以我需要一种方法来区分应用程序是否已经在运行以继续我的其他任务,任何想法?

3 个答案:

答案 0 :(得分:1)

根据@nejinx的回答,你必须在调用Application.launch()时这样做:

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

这样,如果错误发生,您的程序将继续运行,而不是再次尝试启动应用程序。

答案 1 :(得分:0)

您可以执行此操作的唯一方法是捕获IllegalStateException

如果您深入了解JavaFX源代码,您会看到:

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

答案 2 :(得分:0)

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

}

在 JavaFX APP 中:

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

    // Start server
    new MyServer(stage);

    // ...

}