您的位置:首页 > 编程语言 > Java开发

JAVA程序设计(07.3)-----面对对象设计 时钟

2014-10-23 23:59 239 查看
1.面对对象设计 时钟的类  3种录入方式(重载)

package com.lovo;

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

/**
* 时钟 类
* @author Abe
*
*/

/**
* 属性, 小时,分钟,秒
*
* @author Abe
*
*/
public class Clock {
private int hour;
private int min;
private int sec;

/**
* 构造器1 直接输入
*/
public Clock(int hour, int min, int sec) {
this.hour = hour;
this.min = min;
this.sec = sec;
}
/**
* 构造器2 输入字符串 自动分割录入
*
* @param str
*/
public Clock(String str) {
String s1 = str.split(":")[0];
String s2 = str.split(":")[1];
String s3 = str.split(":")[2];
this.hour = Integer.parseInt(s1);
this.min = Integer.parseInt(s2);
this.sec = Integer.parseInt(s3);
}
/**
* 构造器3 默认构造器 录入系统时间
*/
public Clock() {
Calendar cal = Calendar.getInstance();
this.hour = cal.get(Calendar.HOUR_OF_DAY);
this.min = cal.get(Calendar.MINUTE);
this.sec = cal.get(Calendar.SECOND);
}

/**
* 动作:走秒
*/
public Clock go() {
sec++;
if (sec == 60) {
min++;
sec = 0;
}
if (min == 60) {
hour++;
min = 0;
}
if (hour == 24) {
hour = 0;
}
return this;
}
/**
* 动作:倒计时
*/
public Clock back() {
if (sec > 0) {
sec--;
} else if (min > 0) {
min--;
sec = 59;
} else if (hour > 0) {
hour--;
min = 59;
sec = 59;
}
return this;
}
/**
* 输出内存地址 换为字符串
*/
public String toString() {
DecimalFormat df = new DecimalFormat("00");
return df.format(hour) + ":" + df.format(min) + ":" + df.format(sec);

}
}


然后是在弹出窗口中显示倒计时

package com.lovo;
/**
* 时钟在弹出窗口中运行
* @author Abe
*/
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.util.concurrent.Delayed;

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

public class Clockshow {
public static Timer timer = null;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// System.out.printf("请输入现在的时间:");
final Clock c = new Clock("1:0:4");

JFrame j = new JFrame();
j.setSize(600, 480);
j.setResizable(false);
j.setLocationRelativeTo(null);
j.setTitle("小心炸弹");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JLabel lbl = new JLabel("时间", JLabel.CENTER); // 新建内容,填充文字“时间”
// 文字位置居中
Font font = new Font("微软雅黑", Font.PLAIN, 60); // 设置格式 字体,加粗等,大小
lbl.setFont(font); // 文字框调用字体格式
j.setLayout(null); // 开启布局管理器 之后Bounds才能使用
lbl.setBounds(100, 100, 300, 100); // 文字框 位置 大小 开启之后Location才能使用
lbl.setText(c.toString()); // 文字框内容调用c
lbl.setLocation(150, 170); // 位置 顶掉Bounds的位置设置
j.add(lbl);

j.setVisible(true); // 窗口可视

timer = new Timer(500, new ActionListener() { // 这里这里不能手书 选择正确的自动出下面

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
c.back(); // 时钟要干啥,写这里
lbl.setText(c.toString());
if (c.toString().equals("00:00:00")) {
lbl.setText("时间到");//时钟停止显示这个
timer.stop();
}
}
}); // 创建计时器对象
timer.start();// 启动计时器
sc.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: