Using a Java Swing Timer just to delay a function

2019-09-19 14:20发布

问题:

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?

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.)

//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:

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

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

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.



标签: java swing timer