简体   繁体   中英

Have java wait between methods

During my free time, I'm practicing java by making a game. I have a button that calls 2 methods one after the other and both of them alter the same UI object.

I can't find a way/can't understand how to make java wait between execution of the methods so that I could see the value of the field after the first method completes and before it is changed again by the second method.

The way I understand, the best way is to use a swing timer, but I simply didn't understand it's syntax. I tried using sleep, but even though it waited the time specified, it only showed the original and final values, omitting the one in between.

What I have is:

label.setIcon(Alive);

private void cmdAttackActionPerformed(java.awt.event.ActionEvent evt) {
    //inside method1:
    label.setIcon(Dead);

    //wait a few seconds to see the label while setIcon(Dead) is the value

    //inside method2:
    if (reinforcements!=0){
        label.setIcon(Alive);
    }
}

So I tried tinkering some and managed to get results, but I still can't get it to do what I want.

public void run() {
    String output="";
    for (int i = 0; i < combatInfo[info].length(); i++) {
        output=output+combatInfo[info].substring(i, i+1);
        if(i%2==0){
            cmdInfo.setText(output);
            System.out.println(output);
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {}
    }
};

The println() works one step at a time, as it should, however, the setText() still only displays the final value, skipping anything in between. How do I fix that?

Tomas, there have been other users here on stackoverflow with the same (very similar question). I suggest you search before you post.

You can use a Timer as you say, see this answer as an example: java: run a function after a specific number of seconds

Basically you would invoke method1 and use the timer to invoke method2 in the future (scheduled).

最好的方法是使用调试器并设置断点-任何现代IDE都支持:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM