2009-08-20 15 views

回答

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秒後關閉對話框,你會看到文本「對話框關閉」打印到控制檯

+2

您應該在事件分派線程上調用dialog.setVisisble(false)。否則,代碼行爲是不可預知的。 – 2009-08-20 15:55:12

+0

這是非常真實的 - 我爲了混淆的理由而忽略了這一點 – 2009-08-20 16:26:40

3

我會用一個Swing計時器。定時器觸發時,代碼將自動在事件調度線程中執行,GUI的所有更新都應在EDT中完成。

閱讀Swing教程How to Use Timers中的部分。

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