3

我正在创建一个应用程序,在其中测试一定数量的界面功能,当发生错误时,我希望显示一条错误消息。
然后应用程序应该对整个屏幕进行截图,最后在没有用户帮助的情况下关闭错误消息。

为此,我尝试使用 JDialog,如下所示:

    JOptionPane pane = new JOptionPane("Error message", JOptionPane.INFORMATION_MESSAGE);
    JDialog dialog = pane.createDialog("Error");
    dialog.addWindowListener(null);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
    Application.takeScreenshot();
    dialog.setVisible(false);

我想知道是否有特定的方法可以关闭它。我查阅了文档,但似乎找不到。我试图找到关于 SO 的相关问题,但找不到解决我的问题的问题。

我想知道是否有办法获取窗口句柄,然后使用它关闭它,或者只是向窗口发送“CLOSE”或“Press_ok”事件?

编辑:在我看来,当消息框显示时代码完全停止运行,好像有一个 Thread.sleep() 直到用户手动关闭窗口。

如果可能,代码示例会有所帮助。

谢谢

4

2 回答 2

3

尝试使用ScheduledExecutorService. 就像是:

    JDialog dialog = pane.createDialog("Error");
    dialog.addWindowListener(null);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

ScheduledExecutorService sch = Executors.newSingleThreadScheduledExecutor();     
sch.schedule(new Runnable() {
    public void run() {
        dialog.setVisible(false);
        dialog.dispose();
    }
}, 10, TimeUnit.SECONDS);

dialog.setVisible(true); 

[编辑]

关于 camickr 评论,文档没有提到 aScheduledExedcutorService在事件调度线程上执行。所以更好用swing.Timer

JDialog dialog = pane.createDialog("Error");
 dialog.addWindowListener(null);
 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

Timer timer = new Timer(10000, new ActionListener() { // 10 sec
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });

        timer.start();

        dialog.setVisible(true); 
于 2013-10-09T14:08:42.523 回答
1

我已经设法修复它。似乎默认情况下,JDialog 是模态的,这意味着它会中断其他所有内容,直到被用户关闭。为了解决这个问题,我使用了以下方法:

dialog.setModalityType(Dialog.ModalityType.MODELESS);

当它处于活动状态时,一个简单的 .setVisible(false); 足够的。无论如何,感谢您的帮助,抱歉创建了一个不必要的问题,但我已经研究了几个小时,直到我找到它。希望它可以帮助别人。

于 2013-10-09T15:32:54.717 回答