UPDATE #2
嗨伙计们,lemme打破了我的想法 .
当前设置:
-
带有按钮(名为
rootButton
)的primaryStage打开secondaryStage . -
带有按钮(名为
closeButton
)的secondaryStage关闭此secondaryStage . -
closeButton.setCancelButton(true);
使ESC键在secondaryStage上按下closeButton
.
所需功能:
- 在secondaryStage上按ESC键应弹出一个Alert对话框,询问我是否真的要关闭secondaryStage . <<< How to implement?
运行当前代码的结果:
-
当我按下secondaryStage上的ESC键时,警告对话框 doesn't show
-
命令行显示: "Cancel was pressed" .
因此,closeButton以某种方式跳过Alert对话框弹出窗口,而不是直接导致
if (result.get() == ButtonType.CANCEL) {
System.out.println("Cancel was pressed.");
}
那么ESC键事件是否可能从secondaryStage传递到Alert对话框?如果是这种情况, how 和 where 我是否在“警报”对话框中正确使用了此键事件?
当前代码(在GoXr3Plus的帮助下格式化):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Closing extends Application {
// handle primaryStage
@Override
public void start(Stage primaryStage) {
Button rootButton = new Button("show dialog");
// rootButton
rootButton.setOnAction(ac -> {
// CloseButton
Button closeButton = new Button("Close");
closeButton.setCancelButton(true); // make this cancel button
closeButton.setOnAction(a -> {
// Initialize the alert
Alert alert = new Alert(AlertType.CONFIRMATION, "You really want to quit?");
// Show the alert
alert.showAndWait().ifPresent(result -> {
if (result == ButtonType.OK)
System.out.println("OK was pressed.");
else if (result == ButtonType.CANCEL)
System.out.println("Cancel was pressed.");
});
closeButton.getScene().getWindow().hide();
});
StackPane dialogPane = new StackPane(closeButton);
Stage secondaryStage = new Stage();
secondaryStage.setScene(new Scene(dialogPane, 200, 200));
secondaryStage.showAndWait();
});
StackPane rootPane = new StackPane(rootButton);
Scene scene = new Scene(rootPane, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
3 回答
已解决:
正如Ron指出这段代码运行正常 . 我更新到当前版本的Java JDK 1.8.0_91 ,现在所需的ESC键按下确实打开了一个新对话框!谢谢各位的意见!
您可能必须发布所有代码或发布mvce,因为您已经发布的代码完全适合我 . 几乎看起来好像你在某种程度上连续两次紧急逃生 .
尝试将
setOnAction
方法更改为以下内容,并检查输出的标准输出 .你的代码没有编译,所以我修改它看起来更好,并添加了一些评论 . 让我知道它是否做你想要的: