如何使用箭头JavaFX使图像移动

How to make image move using arrows JavaFX

所以基本上我正在导入汽车的图像,并尝试通过使用箭头键向上、向下、向左、向右发出信号来让汽车移动。由于与 swing 和 awt 相比,JavaFX 的使用较少,因此我在 Internet 上可以找到的资源非常少。我是初学者,尝试过但在查看文档时感到困惑。

所以这是我所做的:

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);
  }

}

目前,我正在找出 javaFX 中处理按键的正确语法,如有任何帮助,我将不胜感激。

你可以试试这个 ->

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
});

只需更改 layoutX 属性

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);
    }
  }
});

您可能还对

感兴趣