如何使用箭头JavaFX使图像移动 [英] How to make image move using arrows JavaFX

查看:341
本文介绍了如何使用箭头JavaFX使图像移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这就是我所做的:

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

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

推荐答案

只需更改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检测同时按下的多键键盘按键

这篇关于如何使用箭头JavaFX使图像移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆