【发布时间】:2016-05-21 13:27:20
【问题描述】:
更新 #2
嗨,伙计们,让我和你谈谈我的想法。
当前设置:
- 一个带有按钮(称为
rootButton)的primaryStage,用于打开一个secondaryStage。 - 带有按钮(称为
closeButton)的secondaryStage 可关闭此secondaryStage。 -
closeButton.setCancelButton(true);在secondaryStage 上按下ESC 键触发closeButton。
需要的功能:
- 在 secondaryStage 上按 ESC 键应该会弹出一个警报对话框 问我是否真的要关闭 secondaryStage。 如何实施?
当前代码运行结果:
- 当我按下 ESC 键时,警报对话框不显示 次要阶段
- 命令行显示:“取消被按下”。
因此,closeButton 会以某种方式跳过警报对话框弹出窗口,而是直接导致
if (result.get() == ButtonType.CANCEL) {
System.out.println("Cancel was pressed.");
}
那么ESC键事件是否有可能从secondaryStage传递到Alert对话框?如果是这种情况,我应该如何和在哪里在“警报”对话框中正确使用此关键事件?
当前代码(在 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);
}
}
【问题讨论】:
-
检查它是否使用 System.out.println("Entered on Action method")..
-
DVarga 和 GoXr3Plus,感谢你们的建议。尝试过您的建议后,我会尽力为您提供更多详细信息。
-
@GoXr3Plus 大家好,我刚刚更新了我的代码。我对 stackoverflow 很陌生,但不知何故我无法与他们的代码插入器相处。工作真的很痛苦。无论如何,请看一下,谢谢!
-
@Chiggiddi,当我运行您的代码时(添加必要的导入后),它似乎按预期运行。当我在辅助对话框上按 Escape 时,
Alert对话框出现,我单击确定,警报和辅助对话框消失。现在,话虽如此,在我看来,单击“警报”对话框上的“取消”不应关闭基础对话框。在这种情况下,您必须将closeButton.getScene().getWindow().hide();移动到if (result.get() == ButtonType.OK)构造中。 -
@RonSiven 嗨,罗恩,感谢您与我在一起。现在我终于明白我在以前的帖子中表达得不够清楚。让我解释一下,我需要的功能是能够按 ESC 键(在二级阶段)打开一个警告对话框,询问我是否真的要关闭这个二级阶段。使用当前代码,当我在secondaryStage 上按ESC 时,没有显示警报对话框,随后的命令行显示:“已按下取消”。只有当我在secondaryStage 上单击closeButton 时才会显示警报对话框。