首頁  >  文章  >  Java  >  如何使用計時器在不使用按鈕的情況下從另一個 JFrame 顯示無模式 JDialog?

如何使用計時器在不使用按鈕的情況下從另一個 JFrame 顯示無模式 JDialog?

DDD
DDD原創
2024-10-26 10:59:29254瀏覽

How can I use a timer to display a modaless JDialog from another JFrame without using buttons?

使用不帶按鈕的計時器從另一個JFrame 呼叫一個JFrame

不要使用按鈕來觸發嵌套JFrame 的顯示,而嵌套JFrame是考慮使用無模式對話。該技術提供了一種更清潔、更有效率的方法。

實作:

1.無模式對話框:

  • 創建一個無模式JDialog,它是JDialog,它是一個允許與底層框架互動的頂級容器。

2.倒數計時器:

  • 利用 javax.swing.Timer 啟動倒數計時,在特定時間間隔自動開啟 JDialog。

3. PropertyChangeListener:

  • 為JDialog註冊一個PropertyChangeListener來監聽其value屬性的變化。

4.顯示對話框:

  • 當屬性變更事件被觸發時,隱藏 JDialog 並調度 WINDOW_CLOSING 事件將其關閉。

用例:

以下程式碼片段示範了此技術:

<code class="java">import javax.swing.*;

public class TimedDialogExample {

    // Countdown time in seconds
    private static final int TIME_OUT = 10;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            // Create a frame
            JFrame frame = new JFrame("Main Frame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            // Create a dialog
            JDialog dialog = new JDialog(frame);
            dialog.setSize(300, 200);

            // Create a timer to display the dialog after TIME_OUT seconds
            Timer timer = new Timer(1000, e -> {
                // Hide the dialog
                dialog.setVisible(false);
                // Dispatch a WINDOW_CLOSING event to close the dialog
                dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
            });
            timer.start();

            // Set the dialog's content
            JPanel panel = new JPanel();
            panel.add(new JLabel("This is the dialog"));
            dialog.add(panel);

            // Make the frame visible
            frame.setVisible(true);

            // Display the dialog after TIME_OUT seconds
            timer.stop();
            dialog.setVisible(true);
        });
    }
}</code>

透過採用此技術,您可以自動開啟嵌套的JDialog,而不需要額外的按鈕。這種方法提供了簡化且直觀的使用者體驗,特別是當顯示時間至關重要時。

以上是如何使用計時器在不使用按鈕的情況下從另一個 JFrame 顯示無模式 JDialog?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn