使用线程睡眠和while循环的java中的计时器

时间:2017-04-06 17:48:01

标签: java swing

我正在尝试用Java编写代码来计算时间。我用threadSleep做了一秒钟的延迟。当我运行它冻结一段时间(例如3秒)然后它以毫秒显示结果。我只想知道我应该做些什么来防止冻结和每秒更新文本标签。

import java.awt.*;
import javax.swing.*;

public class Test2 extends JFrame
{
    private JButton btn=new JButton("Start");
    private JLabel lbl=new JLabel("00"); 

    public Test2() {
        super("Timer");
        setLayout(new FlowLayout());
        setSize(400, 500);
        add(lbl);
        add(btn);
        btn.addActionListener(e->{        
            startimer();        
        });
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void startimer() {
        long start=System.currentTimeMillis();
        int i=1;
        while(i<4) {
           try{
                Thread.sleep(1000);
                long now=System.currentTimeMillis();
                lbl.setText("the counter in ms:" + (now-start));
                i=i+1;
            } catch(Exception e){}
        }
     }

      public static void main(String[] args) {
          new Test2().setVisible(true);
      }  
}

1 个答案:

答案 0 :(得分:0)

您需要为您的目的使用Swing worker:

class Test2 extends JFrame {
    private JButton btn=new JButton("Start");
    private JLabel lbl=new JLabel("00");
    public Test2(){
        super("Timer");
        setLayout(new FlowLayout());
        setSize(400, 500);
        add(lbl);
        add(btn);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        btn.addActionListener(e-> new SwingWorker<Object, String>() {
            @Override
            public Object doInBackground() {
                long start = System.currentTimeMillis();
                for(int i = 0; i < 4; i++) {
                    try {
                        Thread.sleep(1000);
                        publish("the counter in ms: " +
                                (System.currentTimeMillis() - start));
                    } catch(Throwable e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void process(final java.util.List<String> chunks) {
                if (!chunks.isEmpty()) {
                    lbl.setText(chunks.get(chunks.size() - 1));
                }
            }
        });
    }
}