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.