![](/img/trans.png)
[英]JavaFX 2.2 JFXPanel in Swing application showing Swing modal dialogs
[英]Make a modal Stage from a JFXPanel within a Swing application
我有一個現有的Swing應用程序,我正在添加JavaFX組件。 我希望我的一個嵌入式JFXPanel
能夠使用Stage
顯示彈出對話框,並且該Stage
將以現有JFrame
作為其所有者進行模態化。
我所做的一個獨立的,可編輯的例子如下。 請注意,我已將Stage
模Modality.APPLICATION_MODAL
設置為Modality.APPLICATION_MODAL
,並已將其所有者設置為JFXPanel
中的Scene
Window
。
如何在Swing應用程序中制作Stage
模態?
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;
}
}
您生成了一個場景對象,將其放置在放置在JFrame內部的JFXPanel中。 同時,您在舞台中放置了與場景主對象相同的場景。
您不能將同一場景同時放在兩個不同的位置。 要創建模態對話框,只需使用Stage對象,因為Stage和JFrame都是來自兩個不同gui庫的頂級容器。
不要將場景添加到JFXPanel和舞台,做一個或另一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.