我正在制作一个 react 时间应用程序,我需要在 GUI 中显示它,所以我需要使用时间轴来执行此操作。除了允许关键帧之间的时间可变之外,我已经使所有内容都可以与时间轴配合使用。
在下面的代码中,我设法在第一个关键帧之后更改它(因此没有等待,然后等待时间为“waitTime”秒)。然后,它使用“waitTime”的值并从此处保持关键帧之间的时间恒定。在代码中,我正在执行更改变量“waitTime”的操作。我只是不确定如何更改关键帧时间。我认为我需要一种递归方法来执行此操作,但尚未找到有关此主题的任何内容。
double waitTime;
Timeline attackChanger = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event){
//randomly generate attack
if(isCountdown = true){
int randI = rand.nextInt(10);
waitTime = randI;
System.out.println(waitTime);
String attack = utils.getRandomAttack();
attackLabel.setText(attack);
}
}
}), new KeyFrame(Duration.seconds(waitTime)));
提前感谢您的回答:)
最佳答案
启动时间轴
后,KeyFrame
就被修复了。即使它们不是,在 java 中也不会通过引用传递基本类型,即 Duration.seconds(waitTime)
返回一个具有恒定持续时间的 Duration
对象,无论您做什么waitTime
稍后。当动画运行时,修改 KeyFrame
列表也没有任何效果。
解决此问题的最佳方法可能是根据新值调整时间线的 rate
属性。
假设你使用
attackChanger.setCycleCount(Animation.INDEFINITE);
在你的动画上:
Timeline attackChanger = new Timeline();
attackChanger.getKeyFrames().addAll(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event){
//randomly generate attack
if(isCountdown = true){
int randI;
// we need treat 0 immediately to avoid
// setting the rate to infinity
// note: in this case only a single
// text value will be displayed and you probably should
// go with (rand.nextInt(9) + 1) to generate values between
// 1 and 9 (inclusive)
// I keep it this way though because of the console output
// and possible side effects of utils.getRandomAttack()
do {
randI = rand.nextInt(10);
waitTime = randI;
System.out.println(waitTime);
String attack = utils.getRandomAttack();
attackLabel.setText(attack);
} while (randI == 0);
// (effective cycle duration) = (standard duration) / rate
attackChanger.setRate(1d / randI);
}
}
}), new KeyFrame(Duration.seconds(1)));
attackChanger.setCycleCount(Animation.INDEFINITE);
//make sure `waitTime` is not 0 at this point
attackChanger.setRate(1d / waitTime);
关于java - 无法使关键帧在时间轴 JavaFX 中变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62544564/