I have an existing Swing application to which I am adding JavaFX components. I would like for one of my embedded JFXPanel
s 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;
}
}