这是我的第一个问题,我是编程新手。我希望这个问题不会让您感到无聊。
我正在为学校项目编写一个 Java 贪吃蛇游戏版本。我正在使用javafx。
每当头吃掉苹果时,就会出现一条文字,然后消失。该文本包括分数(吃掉的苹果的增量)。
文本显示和消失效果很好,但分数总是显示值“0”,尽管它的值不是 0(我可以通过在控制台中打印分数来看到)。
我尝试创建一个 IntValue 类来以另一种方式调用分数的值,但没有成功。
public class MainGame extends Application {
Snake snake = new Snake();
Apple apple = new Apple();
public static final int width = 200;
public static final int height = 200;
public static int score;
private Text tEat = new Text();
public void start(Stage primaryStage) {
Pane layout = new Pane();
ObservableList<Node> components = layout.getChildren(); //creates a list of nodes and adds them to pane
components.add(snake); //snake added to pane
components.add(apple); //apple added to pane
components.add(tEat); //text added to pane
tEat.setText("GG! " + score);
tEat.setFont(Font.font(STYLESHEET_MODENA, FontWeight.BOLD, 20));
tEat.setY(height/2);
tEat.setX(width/2 - 40);
tEat.setFill(Color.GREEN);
tEat.setOpacity(0);
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), ev -> {
snake.move();
if (snake.collides(apple)) {
score++; //score is incremented but not updated in tEat
fader(tEat); //tEat text appears and fades away
snake.eat(apple);
components.remove(apple);
apple = new Apple();
components.add(apple);
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
最佳答案
您可以创建绑定(bind),它会自动更新。
创建:
private LongProperty score = new SimpleLongProperty(0);
然后创建绑定(bind)。
而不是:
tEat.setText("GG! " + score);
使用这个:
tEat.textProperty().bind(Bindings.createStringBinding(() -> ("GG! " + score.get(), score));
而不是这个:
score++;
使用这个:
score.set(score.get() + 1);
这将绑定(bind)您的值,以便每当该属性更新时,它都会更新。
关于java - 在文本javafx中显示变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34514694/