Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

Using a Java Swing Timer just to delay a function

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...