Ste*_*eod 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");
}
}
Run Code Online (Sandbox Code Playgroud)
是的 - 当然可以.你试过安排结束吗?
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");
Run Code Online (Sandbox Code Playgroud)
上述程序将在20秒后关闭对话框,您将看到打印到控制台的文本"Dialog closed"