我可以在Java Swing JDialog框上设置一个计时器,以便在几毫秒后关闭 [英] Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds

查看:121
本文介绍了我可以在Java Swing JDialog框上设置一个计时器,以便在几毫秒后关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好可以创建一个Java Swing JDialog 框(或另一种Swing对象类型),我可以使用它来提醒用户某个事件然后延迟后自动关闭对话框; 没有用户必须关闭对话框?

Hi is it possible to create a Java Swing JDialog box (or an alternative Swing object type), that I can use to alert the user of a certain event and then automatically close the dialog after a delay; without the user having to close the dialog?

推荐答案

此解决方案基于oxbow_lakes',但是它使用javax.swing.Timer,适用于此类事物。它总是在事件派发线程上执行其代码。这对于避免微妙但令人讨厌的错误非常重要

This solution is based on oxbow_lakes', but it uses a javax.swing.Timer, which is intended for this type of thing. It always executes its code on the event dispatch thread. This is important to avoid subtle but nasty bugs

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        final JDialog dialog = new JDialog(f, "Test", true);
        Timer timer = new Timer(2000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        timer.setRepeats(false);
        timer.start();

        dialog.setVisible(true); // if modal, application will pause here

        System.out.println("Dialog closed");
    }
}

这篇关于我可以在Java Swing JDialog框上设置一个计时器,以便在几毫秒后关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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