用Java写一个窗口根据当前时间倒计时为下午五点截至并关闭计算机显示格式为小时分钟秒钟
时间: 2023-05-25 17:01:07 浏览: 70
好的,我来为您展示如何用Java写一个倒计时窗口。
首先,我们需要用Java Swing创建一个窗口,代码如下:
```
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CountdownWindow {
private JLabel countdownLabel;
public CountdownWindow() {
JFrame frame = new JFrame("Countdown");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setLayout(new FlowLayout());
countdownLabel = new JLabel("");
countdownLabel.setFont(new Font("Arial", Font.PLAIN, 36));
frame.add(countdownLabel);
frame.setVisible(true);
countdown();
}
private void countdown() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
// 获取当前时间
Date current = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentTime = sdf.format(current);
// 计算倒计时
long millis = getTimeMillis("17:00:00") - current.getTime();
int hours = (int) (millis / (1000 * 60 * 60));
int minutes = (int) ((millis % (1000 * 60 * 60)) / (1000 * 60));
int seconds = (int) ((millis % (1000 * 60)) / 1000);
// 显示倒计时
countdownLabel.setText(String.format("%02d:%02d:%02d - %s", hours, minutes, seconds, currentTime));
// 判断是否到达截止时间
if (millis <= 0) {
shutdown();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
// 关闭计算机
private void shutdown() {
try {
Runtime.getRuntime().exec("shutdown /s /t 0");
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取指定时间的毫秒值
private long getTimeMillis(String time) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + time;
Date date = sdf.parse(dateString);
return date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
CountdownWindow window = new CountdownWindow();
}
}
```
以上代码会创建一个窗口,显示倒计时和当前时间,并在下午五点时关闭计算机。
希望这个例子可以对您有所帮助。