我实际上学习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