Codester89 Codester89 - 2 months ago 21
Java Question

Closing A JOptionPane Programmatically

I am working on a project in which I would like to close a generic JOptionPane programmatically (by not physically clicking on any buttons). When a timer expires, I would like to close any possible JOptionPane that may be open and kick the user back to the login screen of my program. I can kick the user back just fine, but the JOptionPane remains unless I physically click a button on it.

I have looked on many sites with no such luck. A doClick() method call on the "Red X" of the JOptionPane does not seem possible, and using JOptionpane.getRootFrame().dispose() does not work.

Answer Source

Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:

Action showOptionPane = new AbstractAction("show me pane!") {

    @Override
    public void actionPerformed(ActionEvent e) {
        createCloseTimer(3).start();
        JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
    }

    private Timer createCloseTimer(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;
    }
};