Closing A JOptionPane Programmatically

后端 未结 2 1052
盖世英雄少女心
盖世英雄少女心 2020-11-27 08:16

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 li

相关标签:
2条回答
  • 2020-11-27 08:31

    This code gotten from https://amp.reddit.com/r/javahelp/comments/36dv3t/how_to_close_this_joptionpane_using_code/ seems to be the best approach to me. It involves Instantiating the JOptionPane class rather that using the static helper methods to do it for you. The benefit is you have a JOptionPane object that you can dispose when you want to close the dialog.

    JOptionPane jop = new JOptionPane();
    jop.setMessageType(JOptionPane.PLAIN_MESSAGE);
    jop.setMessage("Hello World");
    JDialog dialog = jop.createDialog(null, "Message");
    
    // Set a 2 second timer
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            dialog.dispose();
        }
    
    }).start();
    
    dialog.setVisible(true);
    
    0 讨论(0)
  • 2020-11-27 08:38

    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;
        }
    };
    
    0 讨论(0)
提交回复
热议问题