倒计时程序
倒计时程序的设计
/*对于一个数字倒计时的设计
* 问题描述:在日常工作中经常见到倒计时的设计,那么,如何设计倒计时呢?
* 给出一个数字,每隔一秒减一,直到减成0为止,并且,数字应该在窗体中显示,
* 或者是直接输出每一次减去的数字,
*
* 问题分析: 窗体的设计比较简单,倒计时的难点在于时间的设计,Java中常用的倒计时设计
* 有三种,
* 一:设置时长的倒计时;
* 二:设置时间戳的倒计时;
* 三:使用java.util.Timer类实现的时间戳倒计时
* 在这个问题中,给定的数字的倒计时要求在每一秒给一个提醒,将数字减一,常见的方式有采用多线程或者Timer()类来实现,
* 在本例中采用多线程来实现,后面会写的关于多线程的整个知识体系,故而采用多线程实现
* Timer()类作为常用类来了解。
*
* 问题解决:设计一个窗体,定义一个文本框和按钮,文本框用来输入要处理的数字,
* 点击按钮用来开始计时,然后定义一个label,用来显示当前的时间点,当时间减为0的时候,
* 在控制板上说明已经减到零,倒计时的实现可以用多线程来设计,
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class tEST1 extends JFrame{
// 定义组件
private JLabel lblTime;
private JTextField txtInput;
private JButton btnEnter;
// 构造方法
public tEST1(){
// 设置窗体的相关属性
super("TimerThread");
this.setSize(300,200);
this.setLayout(null);
this.setLocation(100,50);
// 创建组件
this.lblTime = new JLabel("请输入倒计时时间");
this.lblTime.setBounds(30,20,200,30);
this.txtInput = new JTextField();
this.txtInput.setBounds(30,70,100,30);
this.btnEnter = new JButton("确定");
this.btnEnter.setBounds(150,70,70,30);
// 给JTextField注册监听
this.txtInput.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
public void keyTyped(KeyEvent ke) {
txtInput_KeyTyped(ke);
}
});
// 给JButton注册监听
this.btnEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
btnEnter_ActionPerformed(ae);
}
});
// 将各组件添加到窗体上
add(lblTime);
add(txtInput);
add(btnEnter);
// 显示窗体
this.setVisible(true);
}
// 输入时的事件处理,控制用户只能输入数字
public void txtInput_KeyTyped(KeyEvent ke){
if(ke.getKeyChar() < '0' || ke.getKeyChar() > '9'){
ke.setKeyChar('\0');
}
}
// 点击按钮时的事件处理
public void btnEnter_ActionPerformed(ActionEvent ae){
// 获得用户输入的倒计时时间
String strTime = this.txtInput.getText();
if(strTime.equals("")){
// 检测用户是否输入
this.lblTime.setText("您尚未输入,请输入!");
}
else{
Integer time = Integer.parseInt(strTime);
// 创建线程
TimeThread tt = new TimeThread(this.lblTime,time);
tt.start();
// 创建Timer
/*
Timer timer = new Timer();
timer.schedule(new TimerTask(){
// 启动其他程序
public void run() {
System.out.print("ok");
}
}, time * 1000);
}
}
*/
}
}
// 启动窗体
public static void main(String[] args){
new tEST1();
}
}
// 时间线程类
class TimeThread extends Thread{
private JLabel lblTime;
private int time;
// 构造方法传入,显示事件的JLabel和倒计时的时间。
public TimeThread(JLabel lblTime, int time){
this.lblTime = lblTime;
this.time = time;
}
// run方法
public void run(){
while(time > 0){
// 显示所剩时间
this.lblTime.setText("所剩时间:" + time);
// 所剩时间减少
time--;
try {
this.sleep(1000);//每个一秒计时
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果为:
倒计时中: