java 如何以编程方式关闭消息对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9860731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:40:17  来源:igfitidea点击:

How to close message dialog programmatically?

javaswinguser-interfacejoptionpane

提问by andrew

I have a question about joptionpane.

我有一个关于 joptionpane 的问题。

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

使用 JOptionPane.showMessageDialog(...),我们可以创建一个消息对话框。但是如何以编程方式关闭它?

回答by Hovercraft Full Of Eels

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)

您始终可以通过获取 JOptionPane 所持有的任何组件的 WindowAncestor 来获取对 JOptionPane 的引用,然后在返回的 Window 上调用dispose()setVisible(false)。窗口可以通过使用获得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();
         }
      });
   }
}