java基于GUI的定时关机程序

思路:

利用java调用本地的dos命令,控制定时关机任务,并通过简单的GUI界面设置时长,控制任务进行,取消。代码可直接复制后运行。。


public class Helper extends JFrame implements Runnable{
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();
     }
}
}


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值