Search code examples
javajavafxkeypresseventhandler

How to make image move using arrows JavaFX


So basically I am importing an image of a car and try to make the car move by signalling up, down, left, right by using arrows key. Since JavaFX is less used compared to swing and awt, there are very few resources that I can find on internet. I am beginner and tried but confused when looking at the docs.

So here is what I have done:

public class Car extends Application{

  private int xcoor = 0;
  private int ycoor = 0;
  private int velx  = 0;
  private int vely  = 0;

  @Override 
  public void start(Stage primaryStage) throws Exception{

    Pane pane = new Pane();
    Image carImage = new Image("car.png");
    ImageView cImage = new ImageView(carImage);
    cImage.setFitWidth(120);
    cImage.setFitHeight(80);
    pane.getChildren().addAll(cImage);
    Scene scene = new Scene(pane, 800, 500);


    scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
      @Override
      public void handle(KeyEvent event){

        //How to make the car move with arrow?

      }
    });

    primaryStage.setTitle("Car"); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 

  }


  public static void main(String[] args) {
    launch(args);
  }

}

Currently, I am figuring out the proper syntax in javaFX to handle the keypress, and I would appreciate any help.


Solution

  • Just change the layoutX property

    scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
      @Override
      public void handle(KeyEvent event){
    
        if (event.getCode() == KeyCode.RIGHT) {
            cImage.setLayoutX(cImage.getLayoutX() + 10);
        } else if (event.getCode() == KeyCode.LEFT) {
            cImage.setLayoutX(cImage.getLayoutX() - 10);
        }
      }
    });
    

    You might also be interested in JavaFX Detect mutliple keyboard keys pressed simultaneously