Java Swing.Timer get real time millisecond

情到浓时终转凉″ 提交于 2019-12-02 05:17:11
  1. You will want to get rid of that while (true) and instead use the Swing Timer in its place since that is what the Timer is for -- to repeatedly make calls in a Swing GUI without having to resort to a thread-breaking while (true) construct.
  2. You will want to give your Timer a reasonable delay time. 0? Common sense tells you not to use this. 12, 15 -- better.
  3. For a Swing Timer to work, you need to have an active Swing event thread, and this can be obtained by showing a Swing GUI, any GUI such as a JOptionPane.

For example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

class Lsen implements ActionListener {
   public static final int MSECS_PER_SEC = 1000;
   public static final int SECS_PER_MIN = 60;
   public static final int MIN_PER_HR = 60;
   private static final String TIME_FORMAT = "%02d:%02d:%02d:%03d";

   private long startTime;
   private JTextField timeField;

   public Lsen(JTextField timeField) {
      this.timeField = timeField;
   }

   public void actionPerformed(ActionEvent e) {
      if (startTime == 0L) {
         startTime = System.currentTimeMillis();
      } else {
         long currentTime = System.currentTimeMillis();
         int diffTime = (int) (currentTime - startTime);

         int mSecs = diffTime % MSECS_PER_SEC;
         diffTime /= MSECS_PER_SEC;

         int sec = diffTime % SECS_PER_MIN;
         diffTime /= SECS_PER_MIN;

         int min = diffTime % MIN_PER_HR;
         diffTime /= MIN_PER_HR;

         int hours = diffTime;

         String time = String.format(TIME_FORMAT, hours, min, sec, mSecs);
         // System.out.println("Time: " + time);
         timeField.setText(time);
      }
   }
}

public class StopWatchMain {
   private static final int TIMER_DELAY = 15;

   public static void main(String[] args) {
      final JTextField timeField = new JTextField(10);
      timeField.setEditable(false);
      timeField.setFocusable(false);
      JPanel panel = new JPanel();
      panel.add(new JLabel("Elapsed Time:"));
      panel.add(timeField);

      Lsen l = new Lsen(timeField);
      Timer t = new Timer(TIMER_DELAY, l);
      t.start();
      JOptionPane.showMessageDialog(null, panel);
      t.stop();
   }
}

Edit
You ask about the meaning of the long data type. Please have a look here: Primitive Data Types. You'll see that long means long integer, and so you can think of it as being similar to int but able to tolerate much larger positive and negative values without overflowing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!