User a javax.swing.Timer
. A really simple example is the following:
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
Since JOptionPane dialogs are modal you can take advantage of that if you want and stop the timer when the show method returns. That will cancel the countdown.
Also since they are modal if you really want to use sleep you will have to start a new thread to do it:
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...");
I would recommend Timer over sleep because it is much more flexible. The following is a short JDialog example that provides count down feedback to the user and a 'proper' cancel button:
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();
}
}