KeyPressed JavaFX problem

2

I wanted to trigger an event by pressing the F12 button, but I'm not able to make it fire any action even though I created it in code. Here's an example below.

F12.setOnKeyPressed(event -> {
    if(event.getCode().equals(KeyCode.F12)){
        System.out.println("NN");
    }
});
    
asked by anonymous 19.09.2017 / 16:33

1 answer

1

This happened because you did not define what type of event you are dealing with, this can be done like this:

public class ButtonTest extends Application{

private Button mybutton;

@Override
public void start(Stage primaryStage) throws IOException {

    VBox root = new VBox(5);
    root.setAlignment(Pos.CENTER);

    mybutton = new Button();
    mybutton.setDefaultButton(true);
    mybutton.setOnKeyPressed((KeyEvent t) -> {
        if(t.getCode() == KeyCode.F12){
            System.out.println("F12");
        }
        if(t.getCode() == KeyCode.SPACE){
            t.consume();
        }
    });
    mybutton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            System.out.println("Fired");
        }
    });

    root.getChildren().addAll(mybutton);

    Scene scene = new Scene(root,500,400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

Or using Lambdas:

Button mybutton = new Button();
mybutton.setOnKeyPressed((KeyEvent t) -> {
    if(t.getCode() == KeyCode.F12){
        System.out.println("F12");
    }
});

You can also use this code to consume an event that you do not want to happen like this:

if(t.getCode() == KeyCode.SPACE){
    t.consume();
}

There is no problem with the same button having a setOnAction and a setOnKeyPressed.

    
19.09.2017 / 16:39