我實際上學習JavaFX並試圖做出一個簡單的應用 用箭頭正確地移動一個字符的圖片。JavaFX刷新重新繪製一個新的位置的圖片
我做了onKeyPressed部分這是工作,我可以修改對象的變量locationX和locationY,但圖像不是mooving,有沒有 有點像「repaint()」方法來做到這一點乾脆?或者我必須使用動畫?我寧願暫時不使用動畫。
Fenetre.java
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Fenetre extends Application{
public Charac c1;
public void init(){
c1 = new Charac(110,110);
}
public void start(Stage stage){
ImageView ivChar = new ImageView();
ivChar.setImage(c1.getImg());
ivChar.relocate((double)c1.getLocationX(),(double)c1.getLocationY());
HBox box = new HBox();
box.setTranslateX((double)c1.getLocationX());
box.setTranslateY((double)c1.getLocationY());
box.getChildren().add(ivChar);
box.setFocusTraversable(true);
box.setOnKeyPressed(new EventHandler<KeyEvent>(){
@Override
public void handle(KeyEvent e) {
switch(e.getCode()){
case UP:
c1.goUp();
break;
case DOWN:
c1.goDown();
break;
case LEFT:
c1.goLeft();
break;
case RIGHT:
c1.goRight();
break;
default:
break;
}
}
});
Group root = new Group();
root.getChildren().add(box);
Scene scene = new Scene(root);
scene.setFill(Color.BLACK);
stage.setWidth(600);
stage.setHeight(600);
stage.setTitle("BBMAN");
stage.setScene(scene);
stage.show();
}
}
Charac.java
import javafx.scene.Parent;
import javafx.scene.image.Image;
public class Charac extends Parent{
private int locationX=0;
private int locationY=0;
private Image img = new Image("/Images/bbfront.png");
public Charac(int locationX, int locationY){
this.locationY=locationY;
this.locationX=locationX;
}
public void setLocationX(int locationX){
this.locationX=locationX;
}
public int getLocationX(){
return this.locationX;
}
public int getLocationY(){
return this.locationY;
}
public void setLocationY(int locationY){
this.locationY=locationY;
}
public void goRight(){
this.locationX+=1;
this.img = new Image("/Images/bbright.png");
}
public void goLeft() {
this.locationX-=1;
this.img = new Image("/Images/bbleft.png");
}
public void goUp(){
this.locationY-=1;
this.img = new Image("/Images/bbup.png");
}
public void goDown(){
this.locationY+=1;
this.img = new Image("/Images/bbfront.png");
}
public Image getImg(){
return this.img;
}
}
我不知道RLY如果我在正確的部分我張貼,這是我的第一篇文章。
謝謝大家!
按下按鈕後,您不會更新HBox的位置。 – Steven
相關,也許是重複:[如何編寫JavaFX的KeyListener](http://stackoverflow.com/questions/29962395/how-to-write-a-keylistener-for-javafx),它圍繞屏幕上的按鍵。 – jewelsea