How can i close an JOptionPane automatically?

3.8k Views Asked by At

I want to close a JOptionPane after passed some time, i have tried with dispose(), hide(), and using the command getRootPane().dispose() with no results.

I want to close it after 3 seconds or more so the user don't need to press the button at any time the JOptionPane emerges.

2

There are 2 best solutions below

1
On

You can use one of these statements to hide/close the JFrame.

Frame.setVisible(false);

or

jFrame.dispose();

i.e.

public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setContentPane(new JOptionPane());
        frame.setVisible(true);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            Thread.sleep(5000); //sleep 5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        frame.setVisible(false);
    }
0
On

You can loop over the active windows creating this method on the class you want to do it:

private Timer createTimerClose(int seconds) {
    ActionListener close = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Window[] windows = Window.getWindows();
            for (Window window : windows) {
                if (window instanceof JDialog) {
                    JDialog dialog = (JDialog) window;
                    if (dialog.getContentPane().getComponentCount() == 1
                        && dialog.getContentPane().getComponent(0) instanceof JOptionPane){
                        dialog.dispose();
                    }
                }
            }

        }

    };
    Timer t = new Timer(seconds * 1000, close);
    t.setRepeats(false);
    return t;
}

And after it you call the metod createTimerClose(secondsyouwanttoclose).start(); before calling your JOptionPane.