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

时间:2017-01-25 14:59:53

标签: java javafx keypress eventhandler

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

所以这就是我所做的:

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中用于处理按键的正确语法,我将不胜感激。

2 个答案:

答案 0 :(得分:4)

只需更改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);
    }
  }
});

您可能也对JavaFX Detect mutliple keyboard keys pressed simultaneously

感兴趣

答案 1 :(得分:1)

你可以尝试这个 - &gt;

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