java 倒计时小程序

package com.tomb.web.admin;

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 Test extends JFrame implements Runnable{
    private static final long serialVersionUID = 6L;
    
    private JLabel lbNow, lbNowTitle, lbLeftSecTitle, lbLeftSec, lbLeftMinTitle, lbLeftMin;
    
    private Thread clocker;
    
    public Test(){
        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*9; // 从开始时刻开始 加两个小时
        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(leftSec + " 秒"); //若后面不加字符,可以lbLeftSec.setText(leftSec + ""); 不用String.valueOf
            lbLeftMin.setText(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 Test();
    }
}


你可能感兴趣的:(编程技术,java)