如何在java.util.Timer中留出时间? [英] How to get time left in a java.util.Timer?

查看:121
本文介绍了如何在java.util.Timer中留出时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在util.Timer中留下时间?
我想要做的是添加一个进度条,显示剩余时间,直到计时器重新开始。

How can I get the time left in a util.Timer? What I want to do is to add a progressbar that displays time left until the timer starts over.

这就是我迄今为止所拥有的:

This is what I've got this far:

int seconds = 8;

java.util.Timer timer = new Timer();
timer.schedule( new TimerTask(){
    public void run(){
        // Do something
        // Add a progressbar that displays time left until the timer "starts over".
    },0,(long) (seconds*1000));


推荐答案

你需要第二个计时器来刷新gui in一个特定的间隔。

实现这一目标的另一种方法是每秒激活一个计时器并更新ui中的计数。如果时间到了,请拨打您的具体操作。

You would need a second timer to refresh the gui in a specific interval.
Another way to achieve this, would be to activate a single timer every second and update the counting in the ui. If the time is up, call your specific action.

仅限控制台输出的简单示例:

A simple expample with console output only:

TimerTask task = new TimerTask()
{
    int seconds = 8;
    int i = 0;
    @Override
    public void run()
    {
       i++;

       if(i % seconds == 0)
           System.out.println("Timer action!");
       else
           System.out.println("Time left:" + (seconds - (i %seconds)) );
    }
};

Timer timer = new Timer();
timer.schedule(task, 0, 1000);

它的输出将是:

Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
...

然后只需使用代码更改System.out即可更新进度条。请记住: java.util.Timer 启动自己的线程。 Swing不是线程安全的,所以你需要将每个gui更改代码放入 SwingUtilities.invokeLater()

如果你没有做任何长的话运行任务,每当你的计时器达到8秒标记时,你可能想直接使用 javax.swing.Timer 。它使用EDT而不是它自己的 Thread ,因此您不需要使用 SwingUtilities.invokeLater()将您对Swing组件的调用同步

Then simply change the System.out's with your code to update the progress bar. Remember: java.util.Timer starts its own Thread. Swing is not thread safe, so you need to put every gui changing code into SwingUtilities.invokeLater()!
If you're not doing any long running tasks, every time your timer reachs the 8 seconds mark, you may want to use javax.swing.Timer directly. It uses the EDT and not its own Thread, so you don't need to synchronize your calls to Swing components with SwingUtilities.invokeLater().

另见:

javax.swing.Timer与swing应用程序内的java.util.Timer

这篇关于如何在java.util.Timer中留出时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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