簡體   English   中英

我可以在Java Swing JDialog框上設置一個計時器,以便在幾毫秒后關閉

[英]Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds

您好可以創建一個Java Swing JDialog框(或替代Swing對象類型),我可以使用它來提醒用戶某個事件,然后在延遲后自動關閉對話框; 不必關閉對話框的用戶?

此解決方案基於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");
    }
}

是的 - 當然可以。 你試過安排結束嗎?

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”

我會使用Swing Timer。 當Timer觸發時,代碼將自動在Event Dispatch Thread中執行,GUI的所有更新都應在EDT中完成。

閱讀Swing教程中有關如何使用計時器的部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM