javafx: How to bind the Enter key to a button and fire off an event when it is clicked?

前端 未结 4 1434
忘掉有多难
忘掉有多难 2020-12-16 19:06

Basically, I have a okayButton that sits in a stage and when it is clicked , it performs a list of tasks. Now I want to bind the Enter

4条回答
  •  庸人自扰
    2020-12-16 19:55

    There is a much more simple a standard way to do that using setOnKeyPressed

    okayButton.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.ENTER)) {
                okayButton.fire();
            }
        }
        );
    

    And don't forget that you should define SetOnAction too, other way it's work but it's doing nothing.

    okayButton.setOnAction(event -> {
            // Do what ever you want to your button do. Like :
            System.Out.Print("Okay Button Fired (Clicked or Pressed");
        }
        );
    

提交回复
热议问题