温馨提示×

利用Java的setVisible方法隐藏或显示对话框

小樊
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();
    }
}

在上面的示例中,我们首先创建一个JFrame并在其上放置一个按钮。当点击按钮时,会显示一个JOptionPane对话框。然后通过定时器在3秒后将对话框隐藏。在定时器的回调函数中,我们遍历所有窗口,如果窗口是JDialog类型,则将其设置为不可见。

0