一、程序说明

在实际生活场景中,经常遇到需要电脑自动关机的时候,从网上下载的关机小助手有的好用,但有的不行,而且通常带有广告。其实实现自动关机并不能难,因为可以直接使用cmd命令 “shutdown -s -t 600” 来实现延迟关机,但是每次打开cmd输入命令,太麻烦,而且取消时还要打开cmd,因此用写了一个java程序调用了cmd命令,来实现关机。

程序有两个版本:一个是使用命令行界面的;二是使用swing控件开发的界面程序 ShutGui 1.0

图1: 运行界面

java实现自动关闭订单 java自动关机_java实现自动关闭订单

二、开发步骤

1、首先要为eclipse安装winbuilder插件。这个插件可以不装,但你需要用代码设计界面,有了这个插件就可以直接进行控件拖拽来设计程序界面。


2、新建一个winbuilder - Jframe应用 

图2:新建

java实现自动关闭订单 java自动关机_java实现自动关闭订单_02

3、设计程序主界面,并添加监听类

图3:design

java实现自动关闭订单 java自动关机_java实现自动关闭订单_03

4、编写ShutDownTool类,这个类用来实现定时关机的实际功能。


5、在监听类中调用ShutDownTool类来实现关机功能。


6、修改程序图标、设置托盘图标


7、导出到jar可运行程序; 可以使用 java -jar  shutdown.jar  或 javaw -jar shutdown.jar 来执行jar文件;

      需要的话使用exe4j导出.exe文件


三、项目文件

图4:项目目录结构

java实现自动关闭订单 java自动关机_ico_04

3个java文件:

ShutDownTool.java

package shut;
import java.util.Calendar;
import java.util.Scanner;

class ShutDownTool{
	
	/**
	 * @功能说明 :多少s后关机
	 * @param second  在second 秒之后关机
	 * @return  是否设置成功
	 * @author shaochong
	 * @Date  2014年12月9日 下午4:14:17
	 */
	public boolean shutDownS(int second){
		try {
			String cmdStr = "cmd /c shutdown -s -t "+ second ;
			Runtime.getRuntime().exec(cmdStr);
		}catch(Exception e){
			e.printStackTrace();
			}
		return true;
	}
	
	/**
	 * @功能说明 :在某个时刻关机
	 * @param 时间,格式为 hh:mm
	 * @param today==1 表示当天
	 * 			today==0 表示明天
	 * @return 是否设置成功
	 * @author shaochong
	 * @Date  2014年12月9日 下午4:17:27
	 */
	public boolean shutDownAt(String time, int today){
		Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
		int hour = c.get(Calendar.HOUR_OF_DAY); 
		int minute = c.get(Calendar.MINUTE); 
		
		int hh = Integer.parseInt(time.substring(0,2));
		int mm= Integer.parseInt(time.substring(3,5));
		int k=0;
		if(today==1){
			k = 60*(hh-hour)+(mm-minute);
		}
		if(today==0){
			k = 60*(24-hour)-minute;
			k += hh*60 + mm;
		}
//		System.out.println(k+" 分钟后关机");
		this.shutDownS(k*60);
		
		
		return true;
	}
	/**
	 * @功能说明 :取消定时关机计划
	 * @return 是否成功取消
	 * @author shaochong
	 * @Date  2014年12月9日 下午4:16:25
	 */
	public boolean shutDownCancel(){
		try {
			String cmdStr = "cmd /c shutdown -a" ;
			Runtime.getRuntime().exec(cmdStr);
		}catch(Exception e){
			e.printStackTrace();
			}
		return true;
	}
}




ShutGui.java

package shut;
import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Clock;
import java.util.Calendar;

import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;

public class ShutGui extends JFrame {

	private JPanel contentPane;
	private JTextField textField_time;
	private JTextField textField_show;
	private JTextField textField_delay;
	private JTextField textField_3;
	private JTextField txthhmm;
	private JRadioButton rdbtn_today;
	private JRadioButton rdbtn_tomorrow;
	private ShutDownTool sd = new ShutDownTool();
	private final ButtonGroup buttonGroup = new ButtonGroup();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ShutGui frame = new ShutGui();
					frame.showIcon();
					frame.setVisible(true);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * 显示系统托盘
	 */
	public static void showIcon(){
		if(SystemTray.isSupported()){//判断系统是否托盘
			//创建一个托盘图标对象
			TrayIcon icon = 
			new TrayIcon(Toolkit.getDefaultToolkit().getImage(Clock.class.getResource("/images/21.png")),"ShutDown for Windows");
//			TrayIcon icon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(Clock.class.getResource("/javax/swing/plaf/basic/icons/JavaCup16.png")));
			//创建弹出菜单
			PopupMenu menu = new PopupMenu();
			//添加一个用于退出的按钮
			MenuItem item = new MenuItem("退出");
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
				}
			});
			menu.add(item);
			//添加弹出菜单到托盘图标
			icon.setPopupMenu(menu);
			SystemTray tray = SystemTray.getSystemTray();//获取系统托盘
			try {
				tray.add(icon);
			} catch (AWTException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}//将托盘图表添加到系统托盘
		}
	
	}
	/**
	 * 设置窗口图标
	 */
	public void setWindowIcon()
	{
		ImageIcon imageIcon = new ImageIcon(getClass().getResource("/images/icon.png"));
		this.setIconImage(imageIcon.getImage());
	}
	
	
	/**
	 * Create the frame.
	 */
	private ShutGui() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		this.setTitle("Auto shotdown for Windows");
		setWindowIcon();
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("\u5F00\u59CB");
		menuBar.add(menu);
		
		JMenuItem menuItem_1 = new JMenuItem("\u9000\u51FA");
		menuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 if (JOptionPane.showConfirmDialog(null, "确定退出?") == 0) {
				      System.exit(0);
				     }
			}
		});
		menu.add(menuItem_1);
		
		JMenu menu_1 = new JMenu("\u5E2E\u52A9");
		menuBar.add(menu_1);
		
		JMenuItem menuItem = new JMenuItem("\u5173\u4E8E");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "Author:shaochong \nVersion:1.0\nTime: 2014.12 SDU\nContact:  hao5743@163.com", "关于", JOptionPane.PLAIN_MESSAGE);

			}
		});
		menu_1.add(menuItem);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		textField_time = new JTextField();
		textField_time.setBounds(184, 55, 66, 21);
		contentPane.add(textField_time);
		textField_time.setColumns(10);
		
		textField_show = new JTextField();
		textField_show.setEditable(false);
		textField_show.setBounds(72, 153, 267, 21);
		contentPane.add(textField_show);
		textField_show.setColumns(10);
		textField_show.setText("提示:当前无定时关机计划");
		
		JButton button_cancel = new JButton("\u53D6\u6D88\u5B9A\u65F6\u5173\u673A");
		button_cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				shutDownCancel();
			}
		});
		button_cancel.setBounds(71, 184, 142, 23);
		contentPane.add(button_cancel);
		
		JButton button_set_time = new JButton("\u8BBE\u5B9A\u5173\u673A\u65F6\u95F4");
		button_set_time.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				shutDownAt();
			}
		});
		button_set_time.setBounds(260, 54, 123, 23);
		contentPane.add(button_set_time);
		
		textField_delay = new JTextField();
		textField_delay.setBounds(72, 101, 66, 21);
		contentPane.add(textField_delay);
		textField_delay.setColumns(10);
		
		JButton button_set_delay = new JButton("\u786E\u5B9A");
		button_set_delay.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				shutDownDelay();
			}
		});
		button_set_delay.setBounds(260, 100, 93, 23);
		contentPane.add(button_set_delay);
		
		textField_3 = new JTextField();
		textField_3.setEditable(false);
		textField_3.setText("\u5206\u949F\u540E\u5173\u673A");
		textField_3.setBounds(148, 101, 66, 21);
		contentPane.add(textField_3);
		textField_3.setColumns(10);
		
		txthhmm = new JTextField();
		txthhmm.setEditable(false);
		txthhmm.setText("\u5173\u673A\u65F6\u95F4:(hh:mm)");
		txthhmm.setBounds(72, 55, 102, 21);
		contentPane.add(txthhmm);
		txthhmm.setColumns(10);
		
		rdbtn_today = new JRadioButton("\u4ECA\u5929");
		rdbtn_today.setSelected(true);
		buttonGroup.add(rdbtn_today);
		rdbtn_today.setBounds(72, 25, 59, 23);
		contentPane.add(rdbtn_today);
		
		rdbtn_tomorrow = new JRadioButton("\u660E\u5929");
		buttonGroup.add(rdbtn_tomorrow);
		rdbtn_tomorrow.setBounds(133, 25, 66, 23);
		contentPane.add(rdbtn_tomorrow);
	}
	/**
	 * n分钟后关机
	 */
	public void shutDownDelay(){
		String min = textField_delay.getText();
		if(min.equals("")){
			textField_show.setText("输入为空...");
			return;
		}
		for (int i = 0; i < min.length(); i++) {
			if(!Character.isDigit(min.charAt(i))){
				textField_show.setText("输入数据不合法,请输入数字");
				return;
			}
		}
		int min1 = Integer.parseInt(min);
		if(min1>24*60*2){
			textField_show.setText("延迟关机时间不能超过2天(2880分钟)");
			return;
		}
		if(min1==0) {
			
			int res= JOptionPane.showConfirmDialog(null, "马上关机,确定吗?","确认", JOptionPane.YES_NO_OPTION);
			if(res==0){}
//				JOptionPane.showMessageDialog(null, "关机", "标题条文字串", JOptionPane.ERROR_MESSAGE);
			else{
//				JOptionPane.showMessageDialog(null, "取消了", "标题条文字串", JOptionPane.ERROR_MESSAGE);
				return;
			}
		}
		
		int sec = Integer.parseInt(min)*60;
		int res= JOptionPane.showConfirmDialog(null, min+"分钟后关机, 确定吗?","确认", JOptionPane.YES_NO_OPTION);
		if(res==0){}
		else{
			return;
		}
		
		sd.shutDownS(sec);
		textField_show.setText("提示:"+min+"分钟后关机!");
		textField_delay.setText("");
	}
	
	/**
	 * 在hh:mm时间关机
	 */
	public void shutDownAt(){
		String time = this.textField_time.getText();
		
		if(time.length()!=5){
			textField_show.setText("输入时间格式超长");
			return ;
		}
		if (!time.matches("([0-9]{2}):([0-9]{2})") && !time.matches("([0-9]{2}):([0-9]{2})") ){
			textField_show.setText("输入时间格式不正确");
			return ;
		}
		
		if(time.equals("")){
			textField_show.setText("输入为空...");
			return;
		}
		int hh = Integer.parseInt(time.substring(0,2));
		int mm= Integer.parseInt(time.substring(3,5));
		if(hh>=24 || hh<0){
			textField_show.setText("小时要在0-23之间");
			return;
		}
		if(mm>=60 || mm<0){
			textField_show.setText("分钟要在0-59之间");
			return;
		}
		Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
		int hour = c.get(Calendar.HOUR_OF_DAY); 
		int minute = c.get(Calendar.MINUTE); 
		
		int today=1;
		if(rdbtn_today.isSelected()){
			today=1;
		}
		else if(rdbtn_tomorrow.isSelected()){
			today=0;
		}
		if(today==1 && hh<hour || today==1 && hh==hour && mm<minute ){
			textField_show.setText("输入的今天时间要在当前时间之后");
			return;
		}
		
		if(today==1 && hour==hh && minute==mm){
			int res= JOptionPane.showConfirmDialog(null, "马上关机,确定吗?","确认", JOptionPane.YES_NO_OPTION);
			if(res==0){}
//				JOptionPane.showMessageDialog(null, "关机", "提示", JOptionPane.ERROR_MESSAGE);
			else{
//				JOptionPane.showMessageDialog(null, "取消", "提示", JOptionPane.ERROR_MESSAGE);
				return;
			}
		}
		
		
		String str1 = today==1?"今天":"明天";
		String s="提示:将在"+str1+time+"关机!";
		
		int res= JOptionPane.showConfirmDialog(null, s+" 确定吗?","确认", JOptionPane.YES_NO_OPTION);
		if(res==0){}
		else{
			return;
		}
		
		this.sd.shutDownAt(time, today);
		textField_show.setText(s);
		textField_time.setText("");
	}
	/**
	 * 取消定时关机计划
	 */
	public void shutDownCancel(){
		sd.shutDownCancel();
		textField_show.setText("提示:已取消定时关机计划");
	}
}



ShutDos.java:



package shut;
import java.util.Scanner;

public class ShutDos {
	private ShutDownTool sd = new ShutDownTool();
	public void menu(){
		System.out.println("*************************************");
		  System.out.println("关机助手:");
		  System.out.println("1. 设置关机时间");
		  System.out.println("2. 取消关机");
		  System.out.println("0. Exit.");
		  System.out.println("*************************************");
	}
	
	public void work(){
		Scanner in = new Scanner(System.in);
		boolean f=true;
		while(f){
			this.menu();
			System.out.println("请选择操作:");
			int c=in.nextInt();
			switch(c)
			{
				case(1) : {
					System.out.println("请输入多久后关机:(s为单位)");
					int sec = in.nextInt();
					sd.shutDownS(sec);
					break;
				}
				//余额
				case(2) : {
					sd.shutDownCancel();
					break;
				}
				//取款
				case(0) : {
					System.out.println("退出");
					f = false;
					break;
				}
				
				default:{
					System.out.println("请输入正确选项");
					break;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		ShutDos ts = new ShutDos();
		ts.work();
	}

}