我正在编写一个程序,在显示包含此文本的消息框后,我关闭系统,“你有60秒直到系统关闭”,
但我希望在此框显示运行时间后等待60秒,经过数小时的研究后我无法弄清楚如何做到这一点,我的AP编程老师也不能......
有人可以帮我吗?
我在GUI中这样做,所以我认为需要一个摇摆计时器,但我不确定。
这就是我所拥有的 -
private void Shutdown() throws IOException {
Runtime runtime = Runtime.getRuntime();
JOptionPane.showMessageDialog(null, "You have 60 seconds until system shutdown");
timer = new Timer(60,);
Process proc = runtime.exec("shutdown -s -t 60");
}
private void Logoff() throws IOException {
Runtime runtime = Runtime.getRuntime();
JOptionPane.showMessageDialog(null, "you have 60 seconds until system logoff");
timer = new Timer(60, )
Process proc = runtime.exec("shutdown -l -t 60");
我从点击按钮
调用这些方法答案 0 :(得分:1)
使用Thread.sleep(milliseconds)
答案 1 :(得分:1)
用户a javax.swing.Timer
。一个非常简单的例子如下:
Timer timer = new Timer(60000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/* perform shutdown */
}
});
timer.setRepeats(false);
timer.start();
JOptionPane.showMessageDialog(null, "Shutting down in 60 seconds...");
timer.stop(); // <- optionally cancels the count
由于JOptionPane对话框是模态的,因此如果您想要并在show方法返回时停止计时器,则可以利用它。这将取消倒计时。
另外,因为如果你真的想要使用睡眠它们是模态的,你将不得不开始一个新的线程来做它:
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {}
/* perform shutdown */
}
}).start();
JOptionPane.showMessageDialog(null, "Shutting down in 60 seconds...");
我建议Timer过睡,因为它更灵活。以下是一个简短的JDialog示例,它向用户提供倒计时反馈和“正确的”取消按钮:
public class TimerDialog extends JDialog {
private static final String BEGIN_MSG = "Shutting down in ";
private static final String END_MSG = " seconds...";
private int count = 60;
private JLabel message = new JLabel(BEGIN_MSG + count + END_MSG);
private Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (--count > 0) {
message.setText(BEGIN_MSG + count + END_MSG);
} else {
endCount();
performShutdown();
}
}
});
private TimerDialog() {
setModal(true);
setResizable(false);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
endCount();
}
});
message.setPreferredSize(new Dimension(250, 50));
message.setHorizontalAlignment(JLabel.CENTER);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
endCount();
}
});
JPanel content = new JPanel(new BorderLayout());
JPanel buttons = new JPanel();
buttons.add(cancel);
content.add(message, BorderLayout.CENTER);
content.add(buttons, BorderLayout.SOUTH);
setContentPane(content);
pack();
setLocationRelativeTo(null);
}
private void beginCount() {
timer.start();
setVisible(true);
}
private void endCount() {
timer.stop();
setVisible(false);
dispose();
}
private void performShutdown() {
/* perform shutdown */
}
public static void showAndCountDown() {
new TimerDialog().beginCount();
}
}