gpt4 book ai didi

如果所有者窗口不可见,则 JavaFX 弹出窗口不会显示

转载 作者:行者123 更新时间:2023-12-02 03:02:59 25 4
gpt4 key购买 nike

尝试将 Stage 设置为 Popup 的所有者,但如果所有者不是应用程序的主 Stage,则 Popup 不会出现。

public void popup(Window owner, String mensagem) {
Popup popup = new Popup();
popup.setAutoHide(true);
popup.setHideOnEscape(true);

Label label = new Label(mensagem);
label.setBackground(new Background(new BackgroundFill(Color.CORNSILK, null, null)));

popup.getContent().add(label);
popup.setOnShown((event) -> {
FadeTransition fade = new FadeTransition(Duration.seconds(5), label);
fade.setOnFinished((e) -> {
popup.hide();
});
fade.play();
});

popup.show(owner);
}

子阶段:

public class JanelaModal extends Stage {

public JanelaModal(String title) {
super(StageStyle.DECORATED);
setTitle(title);
initOwner(Main.getInstance().getStage());
initModality(Modality.APPLICATION_MODAL);
setResizable(false);
}

public void setGui(Parent gui) {
if (getScene() != null) {
getScene().setRoot(gui);
} else {
setScene(new Scene(gui));
}
}

}

最佳答案

在显示弹出窗口之前,您必须在子舞台上调用 show(...)

使用您的类JanelaModal我编写了一个简单的测试Java FX应用程序。这是主类

public class Main extends Application {

private static Main instance;
private Stage stage;

@Override
public void start(Stage primaryStage) throws Exception{
instance = this;
this.stage = stage;
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
//primaryStage.show(); //Don't show main stage

JanelaModal modal = new JanelaModal("TEST");
modal.setWidth(300);
modal.setHeight(300);
modal.show();
popup(modal, "Test message");
}

//Copied and pasted from the question post
public void popup(Window owner, String mensagem) {
Popup popup = new Popup();
popup.setAutoHide(true);
popup.setHideOnEscape(true);

Label label = new Label(mensagem);
label.setBackground(new Background(new BackgroundFill(Color.CORNSILK, null, null)));

popup.getContent().add(label);
popup.setOnShown((event) -> {
FadeTransition fade = new FadeTransition(Duration.seconds(5), label);
fade.setOnFinished((e) -> {
popup.hide();
});
fade.play();
});

popup.show(owner);
}

public static void main(String[] args) {
launch(args);
}

public static Main getInstance() {
return instance;
}

public Stage getStage() {
return stage;
}
}

这就是结果

The test application

弹出窗口显示在“子”阶段。如果你打电话

popup(modal, "Test message");

但是你不打电话

modal.show();

弹出窗口(和舞台)将不会显示。

希望我能有所帮助:)

关于如果所有者窗口不可见,则 JavaFX 弹出窗口不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com