您的位置:首页 > 移动开发 > 微信开发

java定时关机小程序

2020-07-05 13:59 405 查看

java定时关机小程序
通过使用java代码实现控制电脑的关机,使用了定时器,可以自定义定时的时长,并且用到了可视化的图形界面,用户可在上方输入定时时长启动任务以及取消。
首先我们编写启动关机和取消关机代码来实现小程序。

/**
* 定时关机小程序
*/
public class Power {
private Runtime r = Runtime.getRuntime();
{
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();
}
}

启动任务已经写好,接下来实现可视化界面,设置标题、窗体等的初始化。

class UI extends JFrame implements ActionListener{
/**启动任务按钮*/
private JButton btnStart; //null
/**取消任务按钮*/
private JButton btnCancel;
/**接收输入的输入框*/
private JTextField inputTime;
/**文本提示控件*/
private JLabel tips;
/**存储当前的剩余时间(秒)*/
private int t;
public UI() {
//设置标题
setTitle("SOFTEEM定时关机小程序");
//设置窗体大小
setSize(360,200);
//设置当前界面显示的相对位置,设置为null时,界面会在屏幕中水平垂直居中
setLocationRelativeTo(null);
//设置禁止窗口大小修改
setResizable(false);
//设置当前窗体总是在最顶层
setAlwaysOnTop(true);
//设置当窗体关闭时的默认操作
setDefaultCloseOperation(EXIT_ON_CLOSE);
//初始化组件
init();
//显示窗体
setVisible(true);
}
/**
* 组件初始化的方法
*/
private void init() {
//设置界面中的布局方式(流式布局)
setLayout(null);
btnStart = new JButton("启动任务");
btnStart.setBounds(20, 60, 150, 40);
btnCancel = new JButton("取消任务");
btnCancel.setBounds(190,60, 150, 40);
inputTime = new JTextField();
inputTime.setBounds(20, 20, 320, 30);
tips = new JLabel("这里显示提示信息!");
tips.setBounds(20, 120, 320, 30);
//将控件加入窗体中
add(btnStart);
add(btnCancel);
add(inputTime);
add(tips);
//为按钮绑定操作指令
btnStart.setActionCommand("start");
btnCancel.setActionCommand("cancel");
//为启动按钮绑定事件(this关键字,多态)
btnStart.addActionListener(this);
//为取消按钮绑定事件
btnCancel.addActionListener(this);
}

创建定时器,来实现定时任务,当任务开启时,界面会有相应的关机计时提示。

Timer timer = new Timer();
TimerTask task = null;
@Override
public void actionPerformed(ActionEvent e) {
//获取被触发事件的控件操作指令
String s = e.getActionCommand();
switch(s) {
case "start":
String time = inputTime.getText();
try {
//当定时任务对象不为空时说明已经有一个正在运行的任务
if(task != null) {
//      tips.setText("请不要重复启动定时任务!");
JOptionPane.showMessageDialog(this, "请不要重复启动定时任务!");
return;
}
t = Integer.parseInt(time);
start(t);
tips.setText(t + "秒之后关机!");
task = new MyTask(t,tips);
//实现倒计时,参考Timer&TimerTask
timer.schedule(task, 0, 1000);
}catch(NumberFormatException ex) {
tips.setText("请输入正确的关机时间(秒)");
}
break;
case "cancel":
if(task == null) {
tips.setText("还未设置关机任务");
return;
}
abort();
tips.setText("计划取消");
//取消任务
task.cancel();
//将引用设置为null
task = null;
break;
}
}

}
public static void main(String[] args) {
new Power();
}

}

启动关机小程序任务。在界面输入时间(秒)后启动任务,界面会有倒计时显示,启动任务后再次启动会有错误提示框弹出,只有取消任务后才可再次启动任务。

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() {
t--;
tips.setText(t+"秒之后自动关机!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: