以编程方式关闭 JOptionPane [英] Closing A JOptionPane Programmatically

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

问题描述

我正在处理一个项目,我想以编程方式(通过不实际单击任何按钮)关闭通用 JOptionPane.当计时器到期时,我想关闭任何可能打开的 JOptionPane 并将用户踢回我的程序的登录屏幕.我可以很好地将用户踢回去,但 JOptionPane 仍然存在,除非我物理点击它上的按钮.

I am working on a project in which I would like to close a generic JOptionPane programmatically (by not physically clicking on any buttons). When a timer expires, I would like to close any possible JOptionPane that may be open and kick the user back to the login screen of my program. I can kick the user back just fine, but the JOptionPane remains unless I physically click a button on it.

我在许多网站上都没有这样的运气.在 JOptionPane 的Red X"上调用 doClick() 方法似乎是不可能的,并且使用 JOptionpane.getRootFrame().dispose() 不起作用.

I have looked on many sites with no such luck. A doClick() method call on the "Red X" of the JOptionPane does not seem possible, and using JOptionpane.getRootFrame().dispose() does not work.

推荐答案

从技术上讲,您可以遍历应用程序的所有窗口,检查它们是否属于 JDialog 类型并具有 JOptionPane 类型的子项,如果是,则处理对话框:

Technically, you can loop through all windows of the application, check is they are of type JDialog and have a child of type JOptionPane, and dispose the dialog if so:

Action showOptionPane = new AbstractAction("show me pane!") {

    @Override
    public void actionPerformed(ActionEvent e) {
        createCloseTimer(3).start();
        JOptionPane.showMessageDialog((Component) e.getSource(), "nothing to do!");
    }

    private Timer createCloseTimer(int seconds) {
        ActionListener close = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Window[] windows = Window.getWindows();
                for (Window window : windows) {
                    if (window instanceof JDialog) {
                        JDialog dialog = (JDialog) window;
                        if (dialog.getContentPane().getComponentCount() == 1
                            && dialog.getContentPane().getComponent(0) instanceof JOptionPane){
                            dialog.dispose();
                        }
                    }
                }

            }

        };
        Timer t = new Timer(seconds * 1000, close);
        t.setRepeats(false);
        return t;
    }
};

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

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