定时关机小程序

Power类:

public class Power{
private Runtime r = Runtime.getRuntime();
{
new UI();
}
public void start(int time){
try{
r.exer(“shutdown -s -t " + time);
}catch(IOExxception e){
e.printStackTrance();
}
}
public void abort(){
try{
r.exec(“shutdown -a”);
}catch(IOException e){
e.printStackTrace();
}
}
class UI extends JFrame implements ActionListener{
private JButton btnStart;
private JButton btnCancel;
private JTextField inputTime;
private JLabel tips;
private int t;
public UI(){
setTitle(“SOFTEEM定时关机小程序”);
setSize(360,200);
setLocationRelativeTo(null);
setResizable(false);
setAlwaysOnTop(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setVisiable(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”);
btnStart.addActionListener(this);
btnCancel.addActionListener(this);
}
Timer timer = new Timer();
TimerTask task = null;
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
switch (s){
case"start”:
String time = inputTime.getText();
try{
if(task != null){
JOptionPane.showMessageDialog(this,“请不要重复启动定时任务”);
return;
}
t = Inter.parseInt(time);
start(t);
tips.setText(t+“秒之后关机!”);
task = new MyTask(t,tips);
timer.schedule(task,0,1000);
}catch(NumberFormatException ex){
tips.setText(“请输入正确的关机时间(秒)”);
}
break;
case “cancel”:
if(task == null){
tips.setText(“还未设置关机任务”);
return;
}
abort();
tips.setText(“取消计划”);
task.cancel();
task = null;
break;
}
}
}
public static void main (String[] args){
new Power();
}
}

MyTask类:
public class MyTask extends TimerTask{
private int t;
private JLabel tips;
public MyTask(int t, JLabel tips){
super();
this.t = t;
this.tips = tips;
}
public void run(){
t–;
tips.setText(t+“秒之后自动关机”);
}
}

猜你喜欢

转载自blog.csdn.net/Wo_I_Java/article/details/107142260
今日推荐