如何以编程方式关闭消息对话框? [英] How to close message dialog programmatically?

查看:135
本文介绍了如何以编程方式关闭消息对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对joptionpane有疑问。

I have a question about joptionpane.

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

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

推荐答案

您可以通过获取它所持有的任何组件的WindowAncestor来获取对JOptionPane的引用,然后在返回的窗口上调用 dispose() setVisible(false)。可以使用获取窗口SwingUtilities.getWindowAncestor(component)

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)

例如:

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

这篇关于如何以编程方式关闭消息对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆