ARiyou Jahan
ARiyou Jahan

Reputation: 1059

Using Enter Key instead of Left Click to fire a Button only when button.isFocused() is true

i write a javaFX program with a button named "okayButton" and every time i click on it, the program will print a message in Command Line.

My main question is how to use this button also by enter only when okayButton.isFocused() returns true

this is a part of my code. where click on button do it's work. same thing that i want by enter :

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

and of course i can use Space Key that is default by java and also windows but i need Enter Key too.

Upvotes: 1

Views: 183

Answers (1)

ARiyou Jahan
ARiyou Jahan

Reputation: 1059

I Found my answer in couple of different pages and i'm going to give you the best and simplest one :

using setOnKeyPressed and Fire methods

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

Don't forget that you must declare the setOnAction() method too.

Upvotes: 2

Related Questions