使用TimeLine每隔一定秒触发一个void方法JavaFX
Use TimeLine to trigger a void method every certain seconds JavaFX
我试图每隔几秒更新一次标签,我尝试使用普通计时器,但由于它在另一个线程中,因此无法更改标签,这就是计时器:
public void setTimer(Timer timer, int seconds, String userName, String content, VBox tabContent,ArrayList<Integer> countTweetsArray, Label statusLabel) {
TabContent tabContentObj = new TabContent();
timer.schedule(new TimerTask() {
@Override
public void run() {
setTweet(userName, content);
//tabContentObj.createStatusScreen(tabContent, countTweetsArray, remainingTweets);
System.out.println(content+" after "+seconds);
System.out.println("countTweetsArray: "+countTweetsArray.get(0));
statusLabel.setText(countTweetsArray.get(0).toString());
countTweetsArray.set(0, (countTweetsArray.get(0)+1));
tabContentObj.timersMap.put(userName, timer);
}
}, (seconds*1000));
}
我读到我可以使用 TimeLine 对标签进行定期更改,但我不明白它如何处理键值和关键帧,有没有一种方法可以在不涉及任何动画的情况下触发 void 方法?
您可以使用带有 Duration
和事件处理程序的 KeyFrame
constructor:
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(seconds), e -> {
// code to execute here...
})
);
timeline.play();
更新:如果你需要一个按钮来停止它,你可以用
Button button = new Button("Stop");
button.setOnAction(e -> timeline.stop());
我试图每隔几秒更新一次标签,我尝试使用普通计时器,但由于它在另一个线程中,因此无法更改标签,这就是计时器:
public void setTimer(Timer timer, int seconds, String userName, String content, VBox tabContent,ArrayList<Integer> countTweetsArray, Label statusLabel) {
TabContent tabContentObj = new TabContent();
timer.schedule(new TimerTask() {
@Override
public void run() {
setTweet(userName, content);
//tabContentObj.createStatusScreen(tabContent, countTweetsArray, remainingTweets);
System.out.println(content+" after "+seconds);
System.out.println("countTweetsArray: "+countTweetsArray.get(0));
statusLabel.setText(countTweetsArray.get(0).toString());
countTweetsArray.set(0, (countTweetsArray.get(0)+1));
tabContentObj.timersMap.put(userName, timer);
}
}, (seconds*1000));
}
我读到我可以使用 TimeLine 对标签进行定期更改,但我不明白它如何处理键值和关键帧,有没有一种方法可以在不涉及任何动画的情况下触发 void 方法?
您可以使用带有 Duration
和事件处理程序的 KeyFrame
constructor:
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(seconds), e -> {
// code to execute here...
})
);
timeline.play();
更新:如果你需要一个按钮来停止它,你可以用
Button button = new Button("Stop");
button.setOnAction(e -> timeline.stop());