使用 Java Swing Timer 只是为了延迟函数 [英] Using a Java Swing Timer just to delay a function

查看:36
本文介绍了使用 Java Swing Timer 只是为了延迟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这是一个回合制战斗序列,每回合的结果输出到一个 JLabel(回合 1:角色 A 对角色 B 造成 8 点伤害.等待 2 秒 第二回合:角色 B 的攻击错过了字符 A.等待 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.)

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

推荐答案

基本上,我只想要一个计时器,在每一步之间停止"一个函数 2 秒.

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

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 只是为了延迟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆