1

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.

ARiyou Jahan
  • 622
  • 6
  • 7

1 Answers1

2

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.

ARiyou Jahan
  • 622
  • 6
  • 7
  • Note that, at least on Windows, I believe pressing _Enter_ works by default since JavaFX 9. Not sure about other platforms (some controls have platform-specific key bindings in order to fit in with the UX of the platform). – Slaw Oct 31 '19 at 03:45
  • I believe the key for firing button events on windows is the spacebar, not sure about javafx 9 or later versions. – SDIDSA Oct 31 '19 at 08:24
  • 1
    @zinouteyar _Space_ works on all platforms, as far as I know. But the standard UX in Windows is that _Enter_ will also fire a button (not just in JavaFX, which is why I think FX9 added that functionality). – Slaw Oct 31 '19 at 11:50