Java Swing How to - Close message dialog programmatically








Question

We would like to know how to close message dialog programmatically.

Answer

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from ww w.  j  a va  2s. c om*/
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
  public static void main(String[] args) {
    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);
  }
}