-->

How to make image move using arrows JavaFX

2019-07-28 17:42发布

问题:

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.

回答1:

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



回答2:

You could try this ->

scene.setOnKeyPressed(e->{
    if(e.getCode()==KeyCode.RIGHT){
          //change the value of x and y appropriately 
          cImage.setLayoutX(x);
          cImage.setLayoutY(y)
    }
    //check for other arrow keys
});