2017-01-25 30 views
1

所以基本上我正在導入一輛汽車的圖像,並試圖通過使用箭頭鍵向上,向下,向左,向右發出信號使汽車移動。由於JavaFX與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中找出正確的語法來處理的按鍵,我希望得到任何幫助。

+0

「_Since JavaFX是很新..._」好一個。 – csmckelvey

+0

@takendarkk我不知道具體的發佈日期,但我知道它正在開始替換GUI的swing和awt。如果它困擾你,我應該改變我的措詞嗎? –

+2

第一個版本於2008年發佈 - 最新版本已出來近3年:) – csmckelvey

回答

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

+0

感謝您的入門代碼,這非常接近我所期待的。 –

1

你可以試試這個 - >

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