在Javafx中输入关键事件不能正常工作?

Vik*_*ngh 2 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");
}
Run Code Online (Sandbox Code Playgroud)

jew*_*sea 8

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

通常情况下,按下时会有一个带焦点的按钮space,而不是enter.但是有一些特殊按钮会在特定按键上激活:默认按钮将亮起,enter并且将触发取消按钮esc.通常,对话框中只有一个特殊类型的按钮中的一个,因此无论当前哪个按钮具有焦点,都可以通过特殊的键盘加速器触发它们.

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

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

ButtonType buttonTypeTwo = new ButtonType(
    "Two",
    ButtonBar.ButtonData.OK_DONE
);
ButtonType buttonTypeThree = new ButtonType(
    "Three",
    ButtonBar.ButtonData.CANCEL_CLOSE
);
Run Code Online (Sandbox Code Playgroud)

请注意,JavaFX系统已自动更改按钮的位置和一些颜色突出显示.当用户按下时enter,则"两个"将触发,当用户按下时esc,则"三个"将触发.如果您在Windows或Linux上运行相同的代码,根据用于这些操作系统的任何按钮定位标准,可能按钮的位置不同.

在此输入图像描述

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

Button buttonTwo = (Button) alert.getDialogPane().lookupButton(buttonTypeTwo);
buttonTwo.setDefaultButton(true);
Button buttonThree = (Button) alert.getDialogPane().lookupButton(buttonTypeThree);
buttonThree.setCancelButton(true);
Run Code Online (Sandbox Code Playgroud)

调整按钮类型

我建议让JavaFX正确定位特定类型的按钮,而不是像上面那样执行查找.

我还建议在JavaFX警报中至少设置一个CANCEL_CLOSE按钮或OK_DONE按钮,否则用户可能很难实际关闭警报,因为对话框可能无法响应用户期望的按键操作.