klearn
klearn

Reputation: 86

JFileChooser doesn't disappear after cancelSelection()

I'm trying to close a JFileChooser. Could you, please, let me know why the cancelSelection method in the following snippet doesn't make it disappear after 5 seconds:

public static void main(String [] args){
    JFrame frame = new JFrame();
    frame.setVisible(true);
    final JFileChooser fchooser = new JFileChooser();
    fchooser.showOpenDialog(frame);
    try {Thread.sleep(5000);} catch (Exception e){}
    fchooser.cancelSelection();
}

Any help is much appreciated.

Upvotes: 0

Views: 220

Answers (3)

foozbar
foozbar

Reputation: 138

I agree that you should use a Swing Timer, but if you want more logic when to disable/dismiss the dialog (for example a progressbar that should close when no more data is available), either implement a SwingWorker or use the following:

  public static void main(String... args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    final JFileChooser fchooser = new JFileChooser();

    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {}

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    // This is run in EDT
                    fchooser.cancelSelection();
                }
            });
        }
    } .start();

    fchooser.showOpenDialog(frame);
}

Upvotes: 2

camickr
camickr

Reputation: 324108

You should use a Swing Timer to do this since updates to the GUI should be done on the Event Dispatch Thread (EDT).

You need to start the Timer BEFORE you invoke the showOpenDialog() method.

Upvotes: 3

Russell Zahniser
Russell Zahniser

Reputation: 16354

The call to showOpenDialog() will not return until a selection is made or the dialog is canceled. If you want to close the dialog after a timeout, you will have to do the timing in another thread.

Upvotes: 2

Related Questions