简体   繁体   English

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

[英]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. 由于与swing和awt相比,JavaFX的使用较少,因此在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. 目前,我正在弄清楚javaFX中用于处理按键的正确语法,希望能对您有所帮助。

Just change the layoutX property 只需更改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);
    }
  }
});

You might also be interested in JavaFX Detect mutliple keyboard keys pressed simultaneously 您可能还对同时按下JavaFX Detect多个键盘按键感兴趣

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM