Answer the question
In order to leave comments, you need to log in
How to handle keyboard events?
I'm trying to make the simplest autoclicker. I can’t figure out how to make it so that when a given key is pressed (in my code it’s space), a click is made.
Here is the test code:
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();
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode()==KeyEvent.VK_SPACE) {
for (int i = 0; i < 3; i++) {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(300);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(300);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Problem solved. I used awt KeyListener library but didn't implement 3 methods keyPressed, keyReleased, keyTyped for it. So I used the javafx.scene.input.KeyEvent library.
In order to listen to the spacebar in JavaFX, I used the following code:
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);
}
}
});
}
}
if (ke.getCode().getName().equals("F12"))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question