- import java.awt.FlowLayout;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- public class TimeCount extends JFrame implements Runnable
- {
- private static final long serialVersionUID = 3484639121843864203L;
- private JLabel lbNow, lbNowTitle, lbLeftSecTitle, lbLeftSec, lbLeftMinTitle, lbLeftMin;
- private Thread clocker;
- public TimeCount()
- {
- this.setLayout(new FlowLayout());
- this.setResizable(false);
- this.setSize(200, 150);
- this.setVisible(true);
- this.setDefaultCloseOperation(EXIT_ON_CLOSE);
- this.setLocation(830, 580);
- initUI();
- clocker = new Thread(this);
- clocker.start();
- }
- private void initUI()
- {
- lbNowTitle = new JLabel("当前时间为:");
- lbNow = new JLabel();
- lbLeftSecTitle = new JLabel("离考试结束还有:");
- lbLeftSec = new JLabel();
- lbLeftMinTitle = new JLabel("离考试结束还有:");
- lbLeftMin = new JLabel("");
-
- this.add(lbNowTitle);
- this.add(lbNow);
- this.add(lbLeftSecTitle);
- this.add(lbLeftSec);
- this.add(lbLeftMinTitle);
- this.add(lbLeftMin);
- }
- public void run()
- {
- SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
- Calendar startCalendar = Calendar.getInstance();
- long startTime = startCalendar.getTime().getTime(); // 获得开始时候的那个时间点
- long endTime = startTime + 2 * 60 * 60 * 1000; // 从开始时刻开始 加两个小时
- long nowTime, leftTime, leftSec, leftMin;
- Calendar now;
-
- while(true)
- {
- now = Calendar.getInstance();
- nowTime = now.getTime().getTime();
- leftTime = endTime - nowTime;
- leftSec = leftTime / 1000;
- leftMin = leftTime / (60 * 1000);
-
- lbNow.setText(dateFormat.format(now.getTime()));
- lbLeftSec.setText(dateFormat.format(leftTime)); //若后面不加字符,可以lbLeftSec.setText(leftSec + ""); 不用String.valueOf
- lbLeftMin.setText(dateFormat.format(leftMin));
-
- if(leftSec == 0)
- {
- JOptionPane.showMessageDialog(this, "对不起!答题时间已到!", "提示", JOptionPane.OK_OPTION);
- break;
- }
-
- try
- {
- Thread.sleep(1000);
- }
- catch(InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args)
- {
- new TimeCount();
- }
- }
复制代码 |
|