简体   繁体   English

Java - 在 for 循环中等待直到方法完成,然后继续

[英]Java - wait in for loop until method finishes, then continue

I need to run through a for loop where the text of a JLabel is set with the counter variable i and after that a Timer method is called.我需要运行一个for循环,其中使用计数器变量i设置JLabel的文本,然后调用Timer方法。 I now want the loop to wait until the method finishes.我现在希望循环等到方法完成。

Code:代码:

public void actionPerformed(ActionEvent arg0) {
    for (int i = 1; i < 6; i++) {
        labelNr.setText(Integer.toString(i));
        startTimer();
    }           
}

Because what it does now is that it instantly sets the text of the JLabel to 5, because it runs through the loop, but starting the timer just in the first loop.因为它现在所做的是立即将JLabel的文本设置为 5,因为它运行在循环中,但仅在第一个循环中启动计时器。

I want the text of the JLabel to be 1 for the first loop, then call the Timer method, then 2 for the second loop, again Timer, 3 for the third loop and so on.我希望JLabel的文本在第一个循环中为 1,然后调用 Timer 方法,然后为第二个循环为 2,再次为 Timer,第三个循环为 3,依此类推。

It basically just needs to wait until the startTimer() method has finished its execution.它基本上只需要等到startTimer()方法完成执行。 I know that synchronized is the possible solution, but I do not know how to implement it properly...我知道 synchronized 是可能的解决方案,但我不知道如何正确实施它...

Thanks in advance.提前致谢。

OK, since I want a quick and dirty answer, it was voted down.好的,因为我想要一个快速而肮脏的答案,所以被否决了。 So how about this:那么这个怎么样:

public void actionPerformed(ActionEvent arg0) {
    changeLabelAndExecuteTask(1)
}

public void changeLabelAndExecuteTask(int i){
    labelNr.setText(Integer.toString(i));
    startTimer(i);
}
public void startTimer(final int i){
    //start a timer here
    new Timer().schedule(new TimerTask(){ 
        @Override 
        void run(){
            methodTimerCall(i)
        }}, 0);
}

public void methodTimerCall(int i){
    //execute things here
    if(++i < 6){
        changeLabelAndExecuteTask(i);
    }
}

forget the under part忘记下面的部分

You can add a static boolean and reset it value by the timer:您可以添加一个静态布尔值并通过计时器重置它的值:

bool waitForTimer = false;
public void actionPerformed(ActionEvent arg0) {
    for (int i = 1; i < 6; i++) {
        waitForTimer = true;
        labelNr.setText(Integer.toString(i));
        startTimer();
        while(waitForTimer){}
    }
}
public void startTimer(){
    //start a timer here
}

public void methodTimerCall(){
    //execute
    waitForTimer = false;
}

一种有效的方法可能是将代码放在 for 循环中的单独方法中,并让“startTime()”方法在执行结束时调用此方法。这样可以保证它在方法完成时准确运行, 而不是在任意时间(即使用 Thread.sleep();)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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