【发布时间】:2017-08-30 12:38:15
【问题描述】:
我实际上正在学习 JavaFX 并尝试制作一个简单的应用程序 用箭头移动一个角色的图片。
我做了 onKeyPressed 部分,它正在工作,我能够修改对象的变量 locationX 和 locationY,但图像没有移动,是否存在 像“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;
}
}
我不知道我是否在正确的部分发帖,这是我的第一篇文章。
谢谢大家!
【问题讨论】:
-
按下按钮后不会更新 HBox 的位置。
-
相关的,可能是重复的:How to write a KeyListener for JavaFX,它在按键时在屏幕上移动一个字符。