10

嗨,是否可以创建一个 Java SwingJDialog框(或替代 Swing 对象类型),我可以用它来提醒用户某个事件,然后在延迟后自动关闭对话框;无需用户关闭对话框?

4

3 回答 3

14

此解决方案基于 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");
    }
}
于 2009-08-20T16:01:31.100 回答
7

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

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 closed”文本

于 2009-08-20T15:18:51.290 回答
3

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

阅读 Swing 教程中有关如何使用计时器的部分。

于 2009-08-20T15:27:08.983 回答