开发工具:eclipse 开发环境:jdk1.8
使用Runtime类中的exec方法在单独的进程中执行指定的字符串命令。
/**创建一个Runtime对象*/ private Runtime r = Runtime.getRuntime(); { UI ui = new UI(); } /** * 启动关机计划 */ public void start(int time) { try { r.exec("shutdown -s -t "+time); } catch (IOException e) { e.printStackTrace(); } } /** * 取消关机计划 */ public void abort() { try { r.exec("shutdown -a "); } catch (IOException e) { e.printStackTrace(); } }参考JFrame类来创建自己需要的图形界面
public class UI extends JFrame implements ActionListener { /**启动任务按钮*/ private JButton btnStart; /**取消任务按钮*/ private JButton btnCancel; /**接收输入的输入框*/ private JTextField inputTime; /**文本提示控件*/ private JLabel tips; /**时间*/ private Timer timer = new Timer(); /**定义一个全局变量*/ private int t; /**定义一个Timertask*/ private TimerTask task = null; public UI() { //设置标题 setTitle("SOFFTEEM定时关机小程序"); //设置窗口大小 setSize(300, 150); //设置当前界面显示的相对位置,设置为null,界面会在屏幕正中间 setLocationRelativeTo(null); //设置禁止窗口大小修改 setResizable(false); //设置当前窗口总是在最顶层 setAlwaysOnTop(true); //设置当窗口关闭时的默认操作 setDefaultCloseOperation(EXIT_ON_CLOSE); //初始化组件 init(); //显示窗口 setVisible(true); }实现ActionListener接口重写actionPerformed方法
@Override public void actionPerformed(ActionEvent e) { //获取被触发事件的控件操作指令 String s = e.getActionCommand(); if(s.equals("start")){ String time = inputTime.getText(); try { //当定时任务对象不为空时说明已经有一个正在运行的任务 if(task != null) { //弹出一个消息界面 JOptionPane.showMessageDialog(UI.this, "请不要重复启动定时任务!"); return; } t = Integer.parseInt(time); start(t); task = new MyTask(t, tips); //实现倒计时,参考Timer&TimerTask timer.schedule(task,0,1000); }catch(NumberFormatException ex) { tips.setText("请输入正确的关机时间(秒)"); } } if(s.equals("cancel")) { if(task == null) { tips.setText("未设置关机任务!"); return; } abort(); tips.setText("计划取消!"); //取消任务 task.cancel(); //将引用设置为null task = null; } } }方便调用run方法
import java.util.TimerTask; import javax.swing.JLabel; public class MyTask extends TimerTask{ private int t ; private JLabel tips; public MyTask(int t, JLabel tips) { super(); this.t = t; this.tips = tips; } @Override public void run() { tips.setText(t-- + "秒之后关机!"); } }
