使用JAVA编写一个计时器

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

public class ReturnTime extends Frame {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Button btnClock;
    public static Label lblClock;
    String strInput;

    // TextField txtClock;
    public ReturnTime() {

 MyEvent me = new MyEvent();

 lblClock = new Label("请点击'设置'按钮",Label.CENTER);
 btnClock = new Button("设置");
 btnClock.addActionListener(me);

 

//添加两个标签
 this.add(lblClock, "Center");
 this.add(btnClock, "South");
 this.pack();

 

//初始化窗体
 setTitle("倒计时表");
 this.setVisible(true);
 this.setResizable(false);
 addWindowListener(me);
    }

    public static void main(String[] args) {
 new ReturnTime();
    }

}

 

 

class MyEvent extends WindowAdapter implements ActionListener {
    String strIn;
    ThreadTime tt;

    public void actionPerformed(ActionEvent ae) {
 //this.setTime();
 //strIn = this.getTime();
 //ReturnTime.lblClock.setText(strIn);
 tt = new ThreadTime(60);
 Thread thread = new Thread(tt);
 thread.start();
    }

    public void setTime() {
 //strIn = JOptionPane.showInputDialog(this, "请输入倒计时的分钟数:");
    }

    /*public String getTime() {
 //return strIn;
  } */
   

//定义窗体关闭事件

    public void windowClosing(WindowEvent we) {
 System.exit(0);
    }
}

 

//使用线程线口Runnable

class ThreadTime implements Runnable {
    //String strIn;
    long time, start, end;

    public ThreadTime(int strIn) {
 //strIn = this.strIn;
 time = (long)(strIn*60000);
 end = time + new Date().getTime();
 
    }

 

//线程主函数

    public void run() {
 while (true) {
     start = end - (new Date().getTime());
     if (start > 0) {
  String strTime = this.convert(start);
  ReturnTime.lblClock.setText(strTime);
  try {
      Thread.sleep(10);
  } catch (InterruptedException ie) {
      ie.printStackTrace();
  }

     } else
  break;
 }
    }

 

//倒计时的详细算法

    public String convert(long ctime) {
 long h = ctime / 3600000;
 long m = (ctime % 3600000)/ 60000;
 long s = (ctime % 60000) / 1000;
 long n = (ctime % 1000)/10;
 String hh = h < 10 ? "0" : "";
 String mm = m < 10 ? "0" : "";
 String ss = s < 10 ? "0" : "";
 String nn = n < 10 ? "0" : "";
 String strTime = hh +h+ ":" + mm +m+ ":" + ss +s+ ":" + nn+n;
 return strTime;
    }
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值