键盘和javafx gui之间的关系(setOnKeyPressed)

时间:2017-03-26 09:11:08

标签: javafx keyboard

我想将JavaFX按钮的动作绑定到键盘键。

enter image description here

我想要以下功能:

  • 当我点击1时,"选择一个文件"应触发
  • 当我点击9时,"选择多个文件"应触发
  • 当我点击Enter时," OK"按钮应该触发
  • 当我点击Esc时,"取消"按钮应该触发

1 个答案:

答案 0 :(得分:1)

Todo,您可以使用EventFilters

如果您希望仅在按下一个键时触发它:

addEventFilter(KeyEvent.KEY_PRESSED, event ->
{
    if(event.getCode().equals(KeyCode.DIGIT1))
    {
        System.out.println("1 Pressed");

        //Then either call the method directly
        selectOneFile();

        //Or fire the button
        selectOneFileBtn.fire();
    }
});

但正如@ItachiUchiha(和我)建议的那样,你应该使用一系列键:

addEventFilter(KeyEvent.KEY_PRESSED, event ->
{
    if(event.isAltDown() && event.getCode().equals(KeyCode.DIGIT1))
    {
        System.out.println("Alt + 1 Pressed");

        //Then again, either call the method directly
        selectOneFile();

        //Or fire the button
        selectOneFileBtn.fire();
    }
});