我试图显示一个计时器(这是一个Text
变量,该变量每秒更新一次),我已经通过时间轴使用了这个简单的time1类。当我使用javafx时,该类起作用。我不明白为什么
timer_text.setText(minutesformatted+":"+secondsformatted);
不起作用。也许是因为Text
变量是static
,但是如果我将其设为static
,则会遇到很多错误。我进行了搜索,发现使用FXML变量时不应将其设置为静态,但这是我可以使用时间轴的唯一方法,还有其他实现计时器的方法。
public class Controller_Experiment
{
public static int minutes;
public static int seconds;
public static int x=0;
Timeline timeline;
@FXML
private static Text timer_text;
@FXML
public void initialize()
{
timer1();
}
@FXML
private void timer1()
{
minutes=5 //starts timer at 5:01
seconds=1;
timeline = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
seconds--;
if (seconds<0){minutes-=1; seconds=59;}
if (minutes<0){minutes=59;seconds=59;}
String minutesformatted = String.format("%02d", minutes);
String secondsformatted = String.format("%02d", seconds);
//this is the part where the text should update, but doesnt work
//if I set text as not static and use it outside the timeline
//it text can be change
//I want to use
// timer_text.setText(minutesformatted+":"+secondsformatted);
x++;
if(minutes==0&&seconds==0)
{
timeline.stop();
}
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
}