javafx - 输入键事件在 Javafx 对话框中不起作用?

标签 javafx javafx-2 javafx-8

我尝试了下面的代码,它可以很好地处理鼠标事件,但是当我使用按键事件(即任何按钮上的 ENTER 键)时,它不会显示结果。

Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle(null);
alert.setHeaderText(null);
alert.setGraphic(null);
alert.setContentText("Choose your option.");

ButtonType buttonTypeOne = new ButtonType("One");
ButtonType buttonTypeTwo = new ButtonType("Two");
ButtonType buttonTypeThree = new ButtonType("Three");

alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne) {
     System.out.println("One");
} else if (result.get() == buttonTypeTwo) {
     System.out.println("Two");
} else if (result.get() == buttonTypeThree) {
     System.out.println("Three");
}

最佳答案

我不建议让所有按钮都响应 enter,因为这与大多数 UI 对话框的工作方式相反。

通常情况下,当您按 空格(而不是回车)时,会触发具有焦点的按钮。然而,有一些特殊的按钮可以在特定的键上激活:A default button将在 entercancel button 上触发将在 esc 上触发。通常,您的对话框中只有这些特殊类型的按钮之一,因此无论当前哪个按钮具有焦点,都可以通过特殊的键盘加速器触发它们。

此外,不同的桌面操作系统对于对话框系统中默认按钮和取消按钮的放置有不同的标准。这是为了帮助用户在任何对话框中轻松找到这些特殊按钮。 JavaFX 对话框系统在内部实现了一些逻辑,用于在对话框中定位按钮,用户希望在不同的桌面操作系统上看到它们。

假设您希望将示例中的按钮类型定义为默认或取消按钮,并将其放置在操作系统中此类按钮的正确位置,那么您可以执行以下操作:

ButtonType buttonTypeTwo = new ButtonType(
    "Two",
    ButtonBar.ButtonData.OK_DONE
);
ButtonType buttonTypeThree = new ButtonType(
    "Three",
    ButtonBar.ButtonData.CANCEL_CLOSE
);

请注意,JavaFX 系统已自动更改按钮的位置和一些颜色突出显示。当用户按 enter 时,将触发“Two”,当用户按 esc 时,将触发“Three”。如果您在 Windows 或 Linux 上运行相同的代码,则按钮的位置可能会有所不同,具体取决于这些操作系统使用的任何按钮定位标准。

enter image description here

如果您不希望 JavaFX 根据操作系统标准重新定位按钮,但希望它们仍然响应 enteresc 键,那么您可以查找按钮并直接修改按钮属性,如下所示:

Button buttonTwo = (Button) alert.getDialogPane().lookupButton(buttonTypeTwo);
buttonTwo.setDefaultButton(true);
Button buttonThree = (Button) alert.getDialogPane().lookupButton(buttonTypeThree);
buttonThree.setCancelButton(true);

adjusted button types

我建议让 JavaFX 适本地定位特定类型的按钮,而不是像上面那样执行查找。

我还建议在 JavaFX 警报中至少设置一个 CANCEL_CLOSE 按钮或 OK_DONE 按钮,否则用户可能很难真正关闭警报,因为对话框可能不会像用户期望的那样响应按键。

关于javafx - 输入键事件在 Javafx 对话框中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35458089/

相关文章:

css - 如何在 javaFX 应用程序中设置组合框提示文本的样式?

javafx-2 - JavaFX 2 : How do I delete a row or column in Gridpane

javafx-2 - JavaFX 一次更新大量按钮的最佳方法是什么?

javafx - 在 JavaFX 2 和 8 之间选择 TableView 期间焦点行为发生变化

JavaFX ComboBox 在使用箭头键时自动填充编辑器文本

在循环内调用appendText()时JavaFx TextArea卡住

java - 在 JavaFX 中使用 Enter 触发按钮的 onAction

java - JavaFX 中的图像碰撞/交叉

java - 具有 JavaFx 进度条行为的 Pb

JavaFX 绑定(bind)不传递值