无需用户操作即可自动关闭Jdialog

问题描述 投票:3回答: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(),直到用户手动关闭了窗口。

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

谢谢

java swing timer jdialog
3个回答
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的评论,文档中没有提到在事件调度线程上执行了ScheduledExedcutorService。所以最好使用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); 

1
投票

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

dialog.setModalityType(Dialog.ModalityType.MODELESS);

当此选项处于活动状态时,一个简单的.setVisible(false);足够。无论如何,感谢您为创建一个不必要的问题所提供的帮助,但是我一直待了好几个小时才找到它。希望它可以帮助别人。


0
投票

@ user2863138我尝试了您的建议,以便使用以下命令自动关闭对话框dialog.setModalityType(Dialog.ModalityType.MODELESS);

此方法向我显示错误“对话框类型中的方法setModalityType(Dialog.ModalityType)不适用于参数(void)”

这是我要执行的代码:

JOptionPane窗格= new JOptionPane(“ Message”);JDialog对话框= pane.createDialog(“顾问”)dialog.setModalityType(dialog.setModalityType(ModalityType.MODELESS)); -我在这条线上看到错误dialog.setVisible(false);dialog.dispose();

© www.soinside.com 2019 - 2024. All rights reserved.