【问题标题】:Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds我可以在 Java Swing JDialog 对话框上设置一个计时器以在几毫秒后关闭吗
【发布时间】:2010-11-21 08:50:35
【问题描述】:

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

【问题讨论】:

    标签: java swing timer scheduler jdialog


    【解决方案1】:

    是的 - 你当然可以。您是否尝试过安排关闭?

    JFrame f = new JFrame();
    final JDialog dialog = new JDialog(f, "Test", true);
    
    //Must schedule the close before the dialog becomes visible
    ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();     
    s.schedule(new Runnable() {
        public void run() {
            dialog.setVisible(false); //should be invoked on the EDT
            dialog.dispose();
        }
    }, 20, TimeUnit.SECONDS);
    
     dialog.setVisible(true); // if modal, application will pause here
    
     System.out.println("Dialog closed");
    

    上述程序将在 20 秒后关闭对话框,您会看到文本“对话框已关闭”打印到控制台

    【讨论】:

    • 您应该在事件调度线程上调用 dialog.setVisisble(false)。否则代码行为是不可预测的。
    • 这是非常正确的-出于混淆的原因我省略了这一点
    【解决方案2】:

    这个解决方案基于 oxbow_lakes',但它使用了一个 javax.swing.Timer,它是为这种类型的东西设计的。它总是在事件调度线程上执行它的代码。这对于避免微妙但令人讨厌的错误很重要

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

    【讨论】:

      【解决方案3】:

      我会使用摇摆计时器。当 Timer 触发时,代码将在 Event Dispatch Thread 中自动执行,所有对 GUI 的更新都应在 EDT 中完成。

      阅读 How to Use Timers 上的 Swing 教程部分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-10
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 2015-12-03
        相关资源
        最近更新 更多