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

   2024-10-01 8560
核心提示:import javax.swing.*;public class DialogExample {public static void main(String[] args) {JFrame frame = new JFrame();fra

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类型,则将其设置为不可见。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号