0

I have a JDialg for showing the progress of a certain task. To display and hide the dialog box I have following methods,

public class ProgressDisplayer extends javax.swing.JDialog {
    ......
    public void s_show() {
            this.setTitle("Month End Status");
            setModal(true);
            setResizable(false);
            pack();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        }

        public void s_hide() {
            this.dispose();
        }

    ...........
}

When I try to close this JDialog box from a Thread as below, although it is displayed properly yet I cannot hide it when I call pd.s_hide() method.

...........
public void run() {            
                ProgressDisplayer pd = new ProgressDisplayer();
                pd.s_show();                    
                Thread.sleep(1000);
                pd.s_hide();
}
.............

please assist me.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Harsha
  • 3,548
  • 20
  • 52
  • 75
  • 1
    *"When .. from a Thread .. is not hide."* Have you confirmed that it hides correctly when **not** called from the thread? Seems like a `setVisible(false);` would not go astray. – Andrew Thompson Sep 07 '12 at 06:18

2 Answers2

5

The reason this doesn't work as you expect is that for modal dialogs, the method setVisible() will block the calling thread until the dialog is closed. This means the calling thread will block on pd.s_show(), and will not continue to the next line (Thread.sleep(1000)) until the user closes the dialog.

The easiest way to fix this is to remove the call to setModal(true). However, you'll lose the modal behavior.

P.S. As radai mentions, it is not thread-safe to call into Swing code from a thread other than the event dispatch thread. Your code is also broken in this sense.

JimN
  • 3,120
  • 22
  • 35
2

swing operations should always be called from the swing event dispatcher thread only. try using SwingUtilities.invokeAndWait() to perform your gui work from non-gui threads. you can see some examples here: http://book.javanb.com/java-threads-3rd/jthreads3-CHP-7-SECT-3.html

radai
  • 23,949
  • 10
  • 71
  • 115