警报
Alert
是一个简单的弹出窗口,它显示一组按钮,并根据用户点击的按钮获取结果:
例
这让用户可以决定是否真的要关闭主要阶段:
@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(new Group(), 100, 100);
primaryStage.setOnCloseRequest(evt -> {
// allow user to decide between yes and no
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Do you really want to close this application?", ButtonType.YES, ButtonType.NO);
// clicking X also means no
ButtonType result = alert.showAndWait().orElse(ButtonType.NO);
if (ButtonType.NO.equals(result)) {
// consume event i.e. ignore close request
evt.consume();
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
请注意,按钮文本会根据 Locale
自动调整。