Here is the code, I want the A key on the keyboard to trigger the action instead of the btn button. How to do it? If possible, write the code as an example.

import java.util.*; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.FlowPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.scene.control.*; public class Dispatcher extends Application { GraphicsContext gc ; Timer t; Button btn; int i=1; public static void main(String[] args) { launch(args); } public void start (Stage myStage){ myStage.setTitle("Game"); FlowPane rootNode = new FlowPane(); rootNode.setAlignment(Pos.CENTER); Scene myScene = new Scene(rootNode,1000,900); myStage.setScene(myScene); Canvas myCanvas = new Canvas(900,800); gc = myCanvas.getGraphicsContext2D(); final TimerTask animation = new TimerTask() { public void run() { gc.setFill(Color.WHITE); gc.fillRect(0,0,900,800 ); i++; gc.setFill(Color.BLACK); gc.fillOval(i ,i+1 ,i ,i+1 ); } }; t = new Timer(); Button btn = new Button("0"); btn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent ae) { t.schedule(animation, 0, 10); } }); rootNode. getChildren ().addAll(myCanvas, btn); myStage.show ( ) ; } } 

    2 answers 2

    It is necessary to hang up the handler for the whole Stage in which to process the necessary behavior.

     myStage.addEventHandler(KeyEvent.KEY_PRESSED, keyEvent - > { if (keyEvent.getCode() == KeyCode.A) { t.schedule(animation, 0, 10); } }); 

    It is also worth noting that if you have some text field and you type there the text that contains the letter A, then the timer will start too. To avoid this, you need to look at which component the event came from. This check allows you to do keyEvent.getSource()

      if you need to imitate a button press, then

       myStage.addEventHandler(KeyEvent.KEY_PRESSED, keyEvent - > { if (keyEvent.getCode() == KeyCode.A) { btn.fire(); } });