尝试将舞台设置为弹出窗口的所有者,但如果所有者不是应用程序的主舞台,则不会显示弹出窗口。
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));
}
}
}
答案 0 :(得分:2)
在显示弹出窗口之前,您必须在您的孩子舞台上调用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;
}
}
这是结果
弹出窗口显示在“子”阶段。如果你打电话
popup(modal, "Test message");
但你不打电话
modal.show();
弹出窗口(和舞台)不会显示。
希望我能帮助,不知何故:)