edvin/tornadofx-guide

Improve swing integration bits

holgerbrandl opened this issue · 5 comments

Not sure if this is the right place to report it, but imho the swing integration docs under https://github.com/edvin/tornadofx/wiki/Integrate-with-existing-Applications could be simplified from doing

public class SwingApp {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JFXPanel wrapper = new JFXPanel();
        frame.getContentPane().add(wrapper);
        frame.pack();
        frame.setVisible(true);

        // Init TornadoFX Application
        Platform.runLater(() -> {
            Stage stage = new Stage();
            MyApp app = new MyApp();
            app.start(stage);
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingApp::createAndShowGUI);
    }
}

to just

public class SwingApp {
    private static void createAndShowGUI() {
         // initialize toolkit
        JFXPanel wrapper = new JFXPanel();
        
        // Init TornadoFX Application
        Platform.runLater(() -> {
            Stage stage = new Stage();
            MyApp app = new MyApp();
            app.start(stage);
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingApp::createAndShowGUI);
    }
}

There is no need (and it's actually confusing) to show another empty JFrame in addition.

edvin commented

Thanks. Not sure who wrote this code initially, but it seems that the point of the extra code is to set the default close operation to EXIT_ON_CLOSE. Are you saying that's already default, so no need to set it? Swing is not my thing (wow, rhymes! :) so I have no experience with it.

The exit behavior could be configured solely on the java-fx level with something like

stage.onCloseRequest = EventHandler<WindowEvent> {
                    Platform.exit()
                    System.exit(0)
                }

as suggested on https://stackoverflow.com/questions/12153622/how-to-close-a-javafx-application-on-window-close

edvin commented

In the initial example the exit behavior for Swing is configured, but in your example the exit behavior for JavaFX is configured. Will this yield the same result? If so, I'll go ahead and update the example.

Yes correct.

The senamtics differ slightly, but I think my solution is more correct. If the close icon of the fxwindow is clicked nothing is happening in the original code. In my suggested version it will close the application.

As stated above, there's a second tiny dummy window (aka the jframe) in the original solution for which the exit behavior was defined. The fx-window close icon did not have any effect.

edvin commented

Thanks for clarifying. I'll update the guide :)