3

I have an existing Swing application to which I am adding JavaFX components. I would like for one of my embedded JFXPanels to be able to display a popup dialog using a Stage, and for that Stage to be modal with the existing JFrame as its owner.

A self-contained, compilable example of what I have done follows. Note that I have set the Stage modality to Modality.APPLICATION_MODAL, and have set its owner to the Window of the Scene within the JFXPanel.

How do I make the Stage modal within the Swing application?

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;

public class App {

    public static void main(String[] args) {
        new App().run();
    }

    public void run() {

        JFrame applicationFrame = new JFrame("JavaFX Mucking");
        applicationFrame.setSize(new Dimension(300, 300));


        JPanel content = new JPanel(new BorderLayout());
        applicationFrame.setContentPane(content);

        JFXPanel jfxPanel = new JFXPanel();
        content.add(jfxPanel);

        Platform.runLater(() -> jfxPanel.setScene(this.generateScene()));

        applicationFrame.setVisible(true);
        applicationFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private Scene generateScene() {
        Button button = new Button("Show Dialog");
        Scene scene = new Scene(new BorderPane(button));

        button.setOnAction(actionEvent -> {
            Stage stage = new Stage(StageStyle.UTILITY);
            stage.initOwner(scene.getWindow());
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setScene(new Scene(new Label("Hello World!")));
            stage.sizeToScene();
            stage.show();
        });

        return scene;
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Timothy McCarthy
  • 857
  • 13
  • 19

1 Answers1

1

You generated a scene object, placed it inside the JFXPanel which was placed inside the JFrame. At the same time you have placed the same Scene as the main Scene object in your Stage.

You cannot have the same Scene be placed in two different places at the same time. To create the modal dialog just use the Stage object, because Stage and JFrame are both top level containers from two different gui libraries.

Do not add the scene to the JFXPanel and the Stage, do one or the other.

Aniket Joshi
  • 115
  • 1
  • 8