我可以在 Java Swing JDialog 框上设置计时器以在几毫秒后关闭吗 [英] Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds
本文介绍了我可以在 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屋!
查看全文