Prevent JavaFX thread from dying with JFXPanel Swing interop?

前端 未结 1 2057
无人共我
无人共我 2020-12-31 22:16

I\'m embedding several JFXPanels into a Swing app and the JavaFX thread dies when the JFXPanels are no longer visible. This is problematic because creating anot

相关标签:
1条回答
  • 2020-12-31 22:35

    This is a really old "bug" that was somewhat fixed with the introduction of Platform.setImplicitExit(false). You can read the developers comments in the open issue JDK-8090517. As you will see it has a low priority and probably will never get fixed (at least not soon).

    Another solution you might want to try instead of using Platform.setImplicitExit(false) is to extend the Application class in your current Main class and use the primary Stage to display the application's main window. As long as the primary Stage remains open the FX Thread will be alive (and dispose correctly when you close your app).

    If you aren't looking to use an FX Stage as your main window (since it would require to use a SwingNode for what you have now or migrate your UI to JavaFX) you can always fake one like this:

    @Override
    public void start(Stage primaryStage) throws Exception {
        YourAppMainWindow mainWindow = new YourAppMainWindow();
        // Load your main window Swing Stuff (remember to use 
        // SwingUtilities.invokeLater() to run inside the Event Dispatch Thread
        mainWindow.initSwingUI();
    
        // Now that the Swing stuff is loaded open a "hidden" primary stage
        // that will keep the FX Thread alive
        primaryStage.setWidth(0);
        primaryStage.setHeight(0);
        primaryStage.setX(Double.MAX_VALUE);
        primaryStage.setY(Double.MAX_VALUE);
        primaryStage.initStyle(StageStyle.UTILITY);
        primaryStage.show();
    }
    

    Keep in mind that faking a primary stage (or migrating your main window to FX) will end in more code than simply using Platform.setImplicitExit(false) and Platform.exit() accordingly.

    Anyway, hope this helps!

    0 讨论(0)
提交回复
热议问题