11

I have a question about joptionpane.

Using JOptionPane.showMessageDialog(...), we can create a message dialog. But how to close it programmatically?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
andrew
  • 885
  • 2
  • 8
  • 16

2 Answers2

22

You could always get a reference to the JOptionPane by getting the WindowAncestor of any component it's holding, and then call dispose() or setVisible(false) on the Window returned. The Window can be obtained by using SwingUtilities.getWindowAncestor(component)

For example:

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class CloseOptionPane {

   @SuppressWarnings("serial")
   private static void createAndShowGui() {
      final JLabel label = new JLabel();
      int timerDelay = 1000;
      new Timer(timerDelay , new ActionListener() {
         int timeLeft = 5;

         @Override
         public void actionPerformed(ActionEvent e) {
            if (timeLeft > 0) {
               label.setText("Closing in " + timeLeft + " seconds");
               timeLeft--;
            } else {
               ((Timer)e.getSource()).stop();
               Window win = SwingUtilities.getWindowAncestor(label);
               win.setVisible(false);
            }
         }
      }){{setInitialDelay(0);}}.start();

      JOptionPane.showMessageDialog(null, label);

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

If you add JOptionPane.showMessageDialog(...) in a While loop use return to close it.

If you add JOptionPane.showMessageDialog(...) try catch block it close when exception happen.

try {
                
    }
catch(Exception ex){
    JOptionPane.showMessageDialog(null, "Please Enter Inputs");             
        }