2009-08-20 23 views

Trả lời

7

Có - tất nhiên bạn có thể. Bạn đã cố gắng sắp xếp lịch biểu chưa?

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

Chương trình trên sẽ đóng hộp thoại sau 20 giây và bạn sẽ thấy dòng chữ "Dialog đóng" in ra cửa sổ Console

+2

Bạn nên gọi dialog.setVisisble (false) trên chuỗi gửi sự kiện. Nếu không, hành vi mã là không thể đoán trước. –

+0

Điều này rất đúng - tôi bỏ qua điều này vì lý do nhầm lẫn –

3

Tôi sẽ sử dụng một Timer Swing. Khi Timer kích hoạt mã sẽ được thực hiện trong Event Dispatch Thread tự động và tất cả các bản cập nhật cho GUI sẽ được thực hiện trong EDT.

Đọc phần từ hướng dẫn xoay trên How to Use Timers.

14

Giải pháp này dựa trên oxbow_lakes ', nhưng nó sử dụng một javax.swing.Timer, được dùng cho loại điều này. Nó luôn thực thi mã của nó trên chuỗi gửi sự kiện. Điều này quan trọng để tránh các lỗi tinh vi nhưng khó chịu

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"); 
    } 
} 
Các vấn đề liên quan