本身Java只用一行代碼就可以設置電腦的計劃關機,取消計劃關機也只需要一行代碼就能搞定了。但本人也是夠閒的,給這個小功能弄了個界面,包括確定和取消按鈕和關機事件的進度條以及一個輸入框。代碼也很簡單:
package javaProject_1;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
public class Demo1 {
public int sec=0;
public int getCurrent(){
//sec++;
return sec++;
}
public void init() {
JFrame jf=new JFrame("自動關機設置");
jf.setLayout(new BorderLayout(30,5));
JPanel jp=new JPanel();
JPanel jp1=new JPanel();
JButton jbOk=new JButton("Ok");
JProgressBar bar=new JProgressBar(JProgressBar.HORIZONTAL);
JButton jbNo=new JButton("Cancel");
JTextField jt=new JTextField(20);
jt.setText("1000");
jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
jp1.setLayout(new BoxLayout(jp1,BoxLayout.X_AXIS));
jp.add(jt);
jp.add(jp1);
jp1.add(jbOk);
Timer timer=new Timer(1000,e->bar.setValue(getCurrent()));
jbOk.addActionListener(event->{
String text="Shutdown -s -t ";
bar.setMaximum(Integer.parseInt(jt.getText()));
try {
Runtime.getRuntime().exec(text+jt.getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.start();
});
jp1.add(Box.createHorizontalGlue());
jp1.add(jbNo);
jbNo.addActionListener(event->{
try {
Runtime.getRuntime().exec("shutdown -a");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bar.setValue(0);
sec=0;
timer.stop();
});
jf.add(jp,BorderLayout.CENTER);
jf.add(new JLabel("請輸入自動關機的時間"),BorderLayout.NORTH);
bar.setMinimum(0);
bar.setMaximum(Integer.parseInt(jt.getText()));
bar.setStringPainted(true);
bar.setBorderPainted(true);
bar.setIndeterminate(false);
//bar.setValue(bar.getMaximum()/2);
jf.add(bar,BorderLayout.SOUTH);
jf.setBounds(300,300,250,120);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.pack();
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new Demo1().init();
}
}
運行效果如圖
就是輸入時間間隔(單位爲秒),然後點擊Ok按鈕電腦會在這個時間後關機,如果不想關機的點擊Cancel按鈕就行了。但如果點確定後關閉窗口,計算機還是會自動關機的。要取消自動關機就要記得點Cancel。