import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 倒計時
*/
public class Counter {
private JFrame frame;
private JLabel jl0;
public static void main(String[] args) throws ParseException {
new Counter().getTime("2017-09-20 21:06:00");
}
/* String -> Date */
private Date String2Date(String dateStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = simpleDateFormat.parse(dateStr);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/* 倒計時的主要代碼塊 */
private void getTime(String dateStr) {
Date end = String2Date(dateStr);
long time = (end.getTime() - 1 - new Date().getTime()) / 1000; // 自定義倒計時時間
long hour = 0;
long minute = 0;
long seconds = 0;
while (time >= 0) {
hour = time / 3600;
minute = (time - hour * 3600) / 60;
seconds = time - hour * 3600 - minute * 60;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<html><br>距離").append(dateStr).append("還有<br><br>")
.append(hour).append("時 ").append(minute).append("分 ").append(seconds).append("秒 ")
.append("</html>");
jl0.setText(stringBuilder.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
time--;
}
}
/* 構造 實現界面的開發 GUI */
public Counter() {
frame = new JFrame("倒計時");
jl0 = new JLabel();
init();
}
/* 組件的裝配 */
private void init() {
JPanel jp = new JPanel();
jp.add(jl0);
frame.add(jp);
frame.setVisible(true);
frame.setLocation(300, 400);
frame.setSize(330, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
java實現倒計時器-圖形界面
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.