我将AnimationTimer
用于诸如更改图片动画和ProgressIndicator
动画之类的多项任务。为了达到所需的速度,我让线程进入休眠状态,但是当同时运行多个动画时,它们会彼此影响速度。还有其他方法可以更改AnimationTimer
的速度吗?代码示例:
private void initialize() {
programButtonAnimation=new AnimationTimer(){
@Override
public void handle(long now) {
showClockAnimation();
}
};
programButtonAnimation.start();
}
private void showClockAnimation(){
String imageName = "%s_"+"%05d"+".%s";
String picturePath="t093760/diploma/view/styles/images/pink_frames/"+String.format( imageName,"pink" ,frameCount,"png");
programButton.setStyle("-fx-background-image:url('"+picturePath+"')");
frameCount++;
try {
Thread.sleep(28);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(frameCount>=120){
programButtonAnimation.stop();
frameCount=0;
}
}
最佳答案
对于FX Application Thread上渲染的每个帧,AnimationTimer
的handle
方法均被调用一次。您永远不要阻塞该线程,因此不要在此处调用Thread.sleep(...)
。
传递给handle(...)
方法的参数是一个时间戳,以纳秒为单位。因此,如果您希望限制更新,以使更新不会每次(例如28毫秒)发生多于一次,则可以执行以下操作:
private void initialize() {
programButtonAnimation=new AnimationTimer(){
private long lastUpdate = 0 ;
@Override
public void handle(long now) {
if (now - lastUpdate >= 28_000_000) {
showClockAnimation();
lastUpdate = now ;
}
}
};
programButtonAnimation.start();
}
private void showClockAnimation(){
String imageName = "%s_"+"%05d"+".%s";
String picturePath="t093760/diploma/view/styles/images/pink_frames/"+String.format( imageName,"pink" ,frameCount,"png");
programButton.setStyle("-fx-background-image:url('"+picturePath+"')");
frameCount++;
if(frameCount>=120){
programButtonAnimation.stop();
frameCount=0;
}
}