This happened because you haven’t defined what kind of event you’re dealing with, it 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 you don’t want to happen this way:
if(t.getCode() == KeyCode.SPACE){
t.consume();
}
No problem a same button have a setOnAction and a setOnKeyPressed.
So bro, it’s still not working. I created the button like this >> private Button F12 = new Button(); << and not there in Scene Builder.Actually this button will not exist on the screen, only a label stating that it will open when you press it.But it is not working.
– TheJ
consume also does not work. Space continues to do the same thing as ENTER
– TheJ
I also didn’t use Scenebuilder in this example, try to instantiate in the controller’s Initialize.
– Gustavo Fragoso
Didn’t work out .
– TheJ
I don’t use FXML to program in Javafx ... but I will edit by putting the whole code for you to test. Buttons that are not on screen or invisible do not trigger actions.
– Gustavo Fragoso
do not shoot? but then complicates kkk pq should shoot right. Because it doesn’t make sense for me to have that function cake and you have to put all these buttons in your window instead of Abels stating what they do.At least the idea was this, just leave a label written and when pressing the F12, open another window
– TheJ
You can put this in a menu and put shortcuts using the Accelerometer
– Gustavo Fragoso
Dude, try to add the event
onKeyPressed
in theanchorPane
and not in thebutton
.– Julio Cesar
Thanks Julio, it worked fine.
– TheJ