java 10.23(时钟)


构造时钟类


package com.lovo;

import java.text.DecimalFormat;
import java.util.Calendar;

/**
 * 时钟类
 * @author 骆昊
 *
 */
public class Clock {
	private int hour;		// 时
	private int minute;		// 分
	private int second;		// 秒
	
	/**
	 * 构造器(获取系统时间)
	 */
	public Clock() {
		Calendar cal = Calendar.getInstance();
		this.hour = cal.get(Calendar.HOUR_OF_DAY);
		this.minute = cal.get(Calendar.MINUTE);
		this.second = cal.get(Calendar.SECOND);
	}
	
	/**
	 * 构造器(获得指定的时间)
	 * @param hour 时
	 * @param minute 分
	 * @param second 秒
	 */
	public Clock(int hour, int minute, int second) {
		this.hour = hour;
		this.minute = minute;
		this.second = second;
	}

	/**
	 * 走字(走一秒)
	 */
	public void go() {
		++second;
		if(second == 60) {
			second = 0;
			++minute;
			if(minute == 60) {
				minute = 0;
				++hour;
				if(hour == 24) {
					hour = 0;
				}
			}
		}
	}
	
	/**
	 * 倒计时
	 * @return 倒计时结束返回true 否则返回false
	 */
	public boolean countDown() {
		if(second > 0) {
			--second;
		}
		else {
			if(minute > 0) {
				--minute;
				second = 59;
			}
			else {
				if(hour > 0) {
					--hour;
					minute = 59;
					second = 59;
				}
			}
		}
		
		return hour == 0 && minute == 0 && second == 0;
	}
	
	/**
	 * 获得时间对象的字符串表示形式
	 */
	public String toString() {
		DecimalFormat df = new DecimalFormat("00");		// 数字格式化器 
		return df.format(hour) + ":" + df.format(minute) + ":" + df.format(second);
	}
}

调用页面

package com.lovo;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;

public class Test01 {
	
	private static Timer timer = null;

	public static void main(String[] args) {
		final Clock c = new Clock(0, 0, 4);
		
		JFrame f = new JFrame();
		f.setTitle("时钟");
		f.setSize(400, 200);
		f.setResizable(false);
		f.setLocationRelativeTo(null);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JLabel lbl = new JLabel("时间", JLabel.CENTER);
		Font font = new Font("微软雅黑", Font.PLAIN, 60);
		lbl.setFont(font);
		lbl.setText(c.toString());
		f.add(lbl);
		
		
		f.setVisible(true);
		
		timer = new Timer(1000, new ActionListener() {
			
			 
			@Override
			public void actionPerformed(ActionEvent e) {
				boolean isOver = c.countDown();
				lbl.setText(c.toString());
				if(isOver) {
					timer.stop();	// 停止计时器
					JOptionPane.showMessageDialog(null, "时间到!!!");
				}
			}
		});		// 创建一个计时器对象
		
		timer.start();		// 启动计时器
	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值