思路:
利用java调用本地的dos命令,控制定时关机任务,并通过简单的GUI界面设置时长,控制任务进行,取消。代码可直接复制后运行。。
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new Helper();
}
String time = null;
JLabel label2;
static int totalTime = 0;
public Helper() {
JLabel jl = new JLabel("欢迎使用",SwingUtilities.CENTER);
Font font = new Font("宋体",Font.BOLD,24);
jl.setFont(font);
jl.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
this.add(jl,BorderLayout.NORTH);
Font font1 = new Font("宋体",Font.BOLD,12);
label2 = new JLabel("定时关机",SwingUtilities.CENTER);
label2.setFont(font1);
label2.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
this.add(label2,BorderLayout.CENTER);
JButton jb1 = new JButton("取消");
jb1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
String[] cmd = new String[]{"cmd.exe","/c","shutdown -a"};
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
e1.printStackTrace();
}
JOptionPane.showMessageDialog(null, "取消成功!");
dispose();
}
});
JButton jb2 = new JButton("确定");
jb2.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
String total = JOptionPane.showInputDialog("请输入定时关机时长!(秒)");
totalTime = Integer.parseInt(total);
String[] cmd = new String[]{"cmd.exe","/c","shutdown -s -t "+totalTime};
try {
Runtime.getRuntime().exec(cmd);
Helper helper = new Helper();
new Thread(helper).start();
helper.setVisible(true);
JOptionPane.showMessageDialog(null, "定时成功!");
dispose();
helper.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JPanel jp_south = new JPanel();
jp_south.add(jb2);
jp_south.add(jb1);
jp_south.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.add(jp_south,BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(200, 300);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
public void run() {
while (true) {
label2.setText("关机倒计时:"+totalTime+"秒");
try {
Thread.sleep(1000);
totalTime = totalTime - 1;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}