Java带图像化界面的倒计时程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* 倒计时
*/
public class Counter {

private JFrame frame;
private JLabel jl0;

private ScheduledThreadPoolExecutor scheduled;

public static void main(String[] args) {
new Counter().timer("2020-02-22 00:00:00");

}

/* String -> Date */
private Date String2Date(String dateStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = simpleDateFormat.parse(dateStr);
if (date.getTime() <= System.currentTimeMillis()) {
jl0.setText("时间不能早于现在" + dateStr);
throw new IllegalArgumentException("时间不能早于现在" + dateStr);
}
return date;
} catch (ParseException e) {
jl0.setText("时间格式传入错误,如yyyy-MM-dd HH:mm:ss," + dateStr);
throw new IllegalArgumentException("时间格式传入错误,如yyyy-MM-dd HH:mm:ss," + dateStr);
}
}


/* 倒计时的主要代码块 */
public void timer(String dateStr) {
Date end = String2Date(dateStr);
scheduled.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long time = (end.getTime() - 1 - System.currentTimeMillis()) / 1000;
if (time <= 0) {
stopTimer();
jl0.setText("到达指定时间点" + dateStr);
return;
}
long hour = time / 3600;
long day=hour / 24;
long minute = (time - hour * 3600) / 60;
long seconds = time - hour * 3600 - minute * 60;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<html>" +
"<h1 style=\"text-align:center\">倒计时</h1><br>" +
"<h2 style=\"text-align:center\">")
.append(day).append("天 ").append(hour- 24*day).append("时 ").append(minute).append("分 ").append(seconds).append("秒 ")
.append("</h2></html>");

jl0.setText(stringBuilder.toString());
}
}, 0, 1, TimeUnit.SECONDS);

}

/**
* 停止定时器
*/
private void stopTimer() {
if (scheduled != null) {
scheduled.shutdownNow();
scheduled = null;
}
}

/* 构造 实现界面的开发 GUI */
public Counter() {
scheduled = new ScheduledThreadPoolExecutor(2);
init();
}

/* 组件的装配 */
private void init() {
frame = new JFrame("XXXXX");
jl0 = new JLabel();

JPanel jp = new JPanel();
jp.add(jl0);

frame.add(jp);

frame.setVisible(true);
frame.setLocation(630, 280);
frame.setSize(400, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}
 wechat
欢迎您扫一扫上面的微信公众号,订阅我的个人公众号!
坚持技术分享!