我有一个现有的 Swing 应用程序,我正在向其中添加 JavaFX 组件。我想要我的嵌入式 JFXPanel
能够使用 Stage
显示弹出对话框,为此 Stage
与现有的 JFrame
模态化作为它的所有者。
下面是我所做的一个独立的、可编译的示例。请注意,我已经设置了 Stage
方式 Modality.APPLICATION_MODAL
,并将其所有者设置为 Window
的 Scene
在 JFXPanel
内.
如何制作 Stage
Swing 应用程序中的模式?
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;
}
}
最佳答案
您生成了一个场景对象,将其放置在 JFXPanel 中,而 JFXPanel 又放置在 JFrame 中。同时,您在舞台中放置了与主场景对象相同的场景。
您不能将同一个场景同时放置在两个不同的地方。要创建模态对话框,只需使用 Stage 对象,因为 Stage 和 JFrame 都是来自两个不同 gui 库的顶级容器。
不要将场景添加到 JFXPanel 和舞台,做一个或另一个。
关于java - 从 Swing 应用程序中的 JFXPanel 创建模态舞台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688855/