首页javajoptionpaneJava Swing - 如何以编程方式关闭消息对话框

Java Swing - 如何以编程方式关闭消息对话框

我们想知道如何以编程方式关闭消息对话框。
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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);
  }
}