To listen to pressing a certain button in JavaFX, you need to use the javafx.scene.input.KeyEvent library:
import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import javafx.scene.input.KeyEvent; import java.awt.Robot; import java.awt.event.InputEvent; public class Main extends Application { Stage window; Robot robot; Scene scene; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { window = primaryStage; window.setTitle("Кликер"); StackPane layout = new StackPane(); robot = new Robot(); scene = new Scene(layout, 200, 100); window.setScene(scene); window.show(); scene.setOnKeyTyped(new EventHandler<KeyEvent>() { public void handle(KeyEvent ke) { if (ke.getCharacter().equals(" ")) for (int i = 0; i < 3; i++) { robot.mousePress(InputEvent.BUTTON1_MASK); robot.delay(300); robot.mouseRelease(InputEvent.BUTTON1_MASK); robot.delay(300); } } }); } }
You cannot catch action buttons like this (such as Ctrl, Shift, function buttons, etc.). But setOnKeyPressed and setOnKeyReleased will catch them too. So, freely replace this line.
scene.setOnKeyTyped(new EventHandler<KeyEvent>() {
On this
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
or this
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
A touch test is replaced by this line
if (ke.getCode().getName().equals("F12"))
Do not depend on the platform layout or keyboard layout. They are generated when a character is entered. In the simplest case of a single key press (eg, 'a'). It can be many--may may Of Of Of Of eg eg eg eg. It is not always necessary to generate a key typed event (eg, entering ASCII sequences via Windows Alt-Numpad method). No key typed events are generated (eg, action keys, modifier keys, etc.).
Official documentation.
Judging by your implementation, you tried to implement the KeyListener interface's KeyListener interface. But even in this case, you would have to do Override on all its 3 methods keyPressed , keyReleased , keyTyped .