1

In Swing for Java 1.5 I want to create a dialog, which allows the user to do other things in background. I want this dialog to have one button, with which you can close the dialog. If the user doesn't close the dialog within X seconds, it should close itself. In both cases a routine has to be done after the dialog has been closed.

I tried to use Swing Timer with a modal dialog and it works. But, as I noticed above, I need a non-modal dialog. When I set the modal-Property to false, the dialog disappears immediately.

Does someone know, why this happens?

JOptionPane pane =  new JOptionPane (text, JOptionPane.WARNING_MESSAGE);
pane.setOptions(new String[]{"Close"});
final JDialog dialog = pane.createDialog(frame, title);
//dialog.setModal(false);

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

dialog.setVisible(true);

//routine to do after the dialog disappears

2 Answers2

2
  1. for better help sooner post an SSCCE, there no code or descriptions about MultiThreading

  2. don't create final JDialog dialog = pane.createDialog(frame, title); on runtime, create this JDialog one time and re_use that for another action, and / or by removing all childs from ContentPane

  3. override proper event from WindowListener, there you can invoke your custom code before dipose(), setVisible() e.i.

  4. (to point 2nd.) simply to override JDialog#setDefaultCloseOperation to HIDE_ON_CLOSE

  5. all code that invoking a new Top-Level Container on runtime must be wrapped into invokeLater(), especially setVisible(true)

  6. use Application Inactivity by @camickr

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • The example cited [here](http://stackoverflow.com/a/12694503/230513) uses a `JOptionPane` directly in a modeless dialog. – trashgod Oct 02 '12 at 16:43
2

In this example, a modeless JDialog containing a direct JOptionPane counts down to zero before closing. A nearby JFrame containing a label remains responsive.

Addendum: As @mKorbel helpfully comments, your class can use a PropertyChangeListener to learn when the dialog's option pane closes. This is a convenient feature of JOptionPane, but you can add your own support, as shown here.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045