optimist_creeper optimist_creeper - 6 months ago 22
Java Question

Timed JDialog is not closing after specified time

I was searching for timed JDialog which will disappear after a specified time has been elapsed and the code found is running ok.

JFrame f = new JFrame();
final JDialog dialog = new JDialog(f, "Test", true);
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();

dialog.setVisible(true);


But after changing the code as below is not working i.e. the modal is not being closed after specified time has elapsed:

JFrame f = new JFrame();
final JDialog dialog = new JDialog(f, "Test", true);

dialog.setVisible(true);

Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();


I can't get why it's happening. Please, if someone explain the cause it would be of great help.

Thanks in advance.

Answer

Because in the second program, the call of dialog.setVisible(true); is blocking when the dialog is modal, i.e. the execution stops there here until you close the dialog. So, the timer will not start until you close the dialog manually. The first program is the solution. Why doing the second?