java实现电脑系统关机功能代码
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ShutdownComputer {
public static void main(String[] args) {
JFrame frame = new JFrame("关机按钮");
JButton button = new JButton("关机");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(frame, "确定要关机吗?", "确认关机", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
try {
// 关闭计算机
Runtime.getRuntime().exec("shutdown -s -t 0");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
该代码创建了一个带有一个按钮的窗口,当用户点击按钮时,将弹出一个确认对话框,询问用户是否要关机。如果用户点击了"是"按钮,将会执行关机命令。如果用户点击了"否"按钮,将不会执行任何操作。