使用Java Swing Timer只是为了延迟一个函数

时间:2022-11-30 20:32:27

Basically, I just want a timer that ''stops'' a function for 2 seconds between each step. I don't want it to call any other task/method, I just want it to pause execution. What's the best way of doing this?

基本上,我只想要一个计时器,在每一步之间“停止”一个2秒的功能。我不希望它调用任何其他任务/方法,我只是想让它暂停执行。这样做的最佳方法是什么?

It's for a turn based battle sequence where the results of each turn are output to a JLabel (Turn 1: Character A hits character B for 8 damage. wait 2 seconds Turn 2: Character B's attack misses character A. wait 2 seconds etc.)

这是一个基于回合的战斗序列,其中每个回合的结果输出到JLabel(转弯1:角色A命中角色B进行8次伤害。等待2秒转2:角色B的攻击未命中角色A.等待2秒等)

//Battle/////////////////////////

    int aDmg = aAttackPower - d.def;
    double aHitChance = aHitRate - dAvoidRate;
    String sound;

    //Turn 1

    if (aHitChance >= rngs[rngsIndex]) {

        if (aCritRate >= rngs[rngsIndex]) {
            aDmg *= 3;
            sound="crit.wav";
            t.print("Critical Hit! " + a.name + " attacks " + d.name + " for " + aDmg + " damage!");
            rngsIndex++;
        } else {
            sound="hit.wav";
            t.print(a.name + " attacks " + d.name + " for " + aDmg + " damage!");
            rngsIndex++;
        }

        d.damageHp(aDmg);
        rngsIndex++;
    } else {
        sound = "miss.wav";
        t.print(a.name + " has missed.");
        rngsIndex++;
    }

    playSound(sound);

    //Timer 2 seconds <---- Timer would go here
    //Turn 2

1 个解决方案

#1


1  

Basically, I just want a timer that ''stops'' a function for 2 seconds between each step.

基本上,我只想要一个计时器,在每一步之间“停止”一个2秒的功能。

That is not the way a Timer works. A Timer does not stop processing. A Timer generates an event that you can handle.

这不是Timer的工作方式。计时器不会停止处理。计时器生成您可以处理的事件。

You want a timer such that every time it fires you invoke a different step.

你想要一个计时器,每次它触发时你都会调用一个不同的步骤。

So you need to keep a counter. Every time the timer fires you test the value of the counter and invoke the appropriate step, then you increment the counter.

所以你需要保留一个柜台。每次计时器触发时,您都会测试计数器的值并调用相应的步骤,然后递增计数器。

You then stop the Timer when you reach the specified number of steps.

然后在达到指定的步数时停止计时器。

#1


1  

Basically, I just want a timer that ''stops'' a function for 2 seconds between each step.

基本上,我只想要一个计时器,在每一步之间“停止”一个2秒的功能。

That is not the way a Timer works. A Timer does not stop processing. A Timer generates an event that you can handle.

这不是Timer的工作方式。计时器不会停止处理。计时器生成您可以处理的事件。

You want a timer such that every time it fires you invoke a different step.

你想要一个计时器,每次它触发时你都会调用一个不同的步骤。

So you need to keep a counter. Every time the timer fires you test the value of the counter and invoke the appropriate step, then you increment the counter.

所以你需要保留一个柜台。每次计时器触发时,您都会测试计数器的值并调用相应的步骤,然后递增计数器。

You then stop the Timer when you reach the specified number of steps.

然后在达到指定的步数时停止计时器。