【发布时间】:2017-03-14 20:04:39
【问题描述】:
我想要一个计数到 3 的计数器,然后它应该从 0 重新开始并无限期地重复计数直到 3。
但是当我的计数器达到 3 时,我的程序所做的最后一件事就是设置文本 "0"。
我想我没有正确使用动画。
我希望有人知道我做错了什么。
请注意,这只是对我的实际问题的简化;可能有更简单的方法来数到 3...
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class GeneralTesting extends Application{
private Text text;
private int counter = 1;
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
text = new Text(500, 300, "0");
text.setFont(Font.font("Comic Sans MS", FontWeight.BOLD, FontPosture.REGULAR, 100));
Animation animation = new Timeline(new KeyFrame(Duration.millis(1000), e -> {changeText(counter++);}));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
pane.getChildren().addAll(text);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
public void changeText(int counter){
if (counter > 5){
counter = 0;
}
text.setText(String.valueOf(counter));
}
}
【问题讨论】: