简体   繁体   中英

Make a modal Stage from a JFXPanel within a Swing application

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM