利用Java的setVisible方法隱藏或顯示對(duì)話框

小樊
83
2024-08-23 11:29:27

import javax.swing.*;

public class DialogExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 200);
        
        JButton button = new JButton("Show Dialog");
        button.addActionListener(e -> {
            JOptionPane.showMessageDialog(frame, "Hello, this is a dialog!");
        });
        
        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        
        // Hide the dialog after 3 seconds
        Timer timer = new Timer(3000, e -> {
            Window[] windows = Window.getWindows();
            for (Window window : windows) {
                if (window instanceof JDialog) {
                    window.setVisible(false);
                }
            }
        });
        timer.setRepeats(false);
        timer.start();
    }
}

在上面的示例中,我們首先創(chuàng)建一個(gè)JFrame并在其上放置一個(gè)按鈕。當(dāng)點(diǎn)擊按鈕時(shí),會(huì)顯示一個(gè)JOptionPane對(duì)話框。然后通過(guò)定時(shí)器在3秒后將對(duì)話框隱藏。在定時(shí)器的回調(diào)函數(shù)中,我們遍歷所有窗口,如果窗口是JDialog類型,則將其設(shè)置為不可見。

0