开发者

(Java Swing) Calling function in time intervals and displaying time to next call in label

I have function like this in Java Swing app. I need after click on button call many function in intervals and in cycles. Function must be called inside jbutton because I have some global parameters in View that are used in jbutton function. Can you please help me how can I create time delay between calling functions and how to display remaining time in jLabel?

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

        statusMessageLabel.setText("Proccess started.");
        for(int i=0;i< cycles;i++) {

    开发者_如何转开发        //display remaining time
            jLabelTimer.setText("00:09:59");
            // after time call many functions and then go again
            manyFunctions();

        } catch (Exception e) {
            System.out.println(e);
        }
        statusMessageLabel.setText("Proccess ended.");
        }
}


I agree with Howard's recommendation that a Swing Timer could work well here (1+), but my other concern with your code is here:

manyFunctions();

What exactly is going on at this spot? Are you calling lots of code that is time/cpu-consuming? If so, you will need to take care not to call this on the main Swing thread, the EDT, but rather call it in a background thread, but at the same time taking are to update Swing components only on the EDT. This can be simplified by using a SwingWorker, and you can read up more on this here: Concurrency in Swing


It sounds like you want to have a look at swing timers. With those you can schedule single calls or do them periodically.

This way you can also add a timer which resets your label text periodically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜