无法使 KeyFrame 在 Timeline JavaFX 中变化

Cannot make the KeyFrame vary in Timeline JavaFX

我正在制作一个反应时间应用程序,我需要在 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)));

提前感谢您的任何回答:)

启动 Timeline 后,KeyFrame 已修复。即使它们不存在,在 java 中也没有通过引用传递原始类型,即 Duration.seconds(waitTime) returns 具有恒定持续时间的 Duration 对象,无论您对 [=16 做什么=] 稍后。虽然动画 运行 修改 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);