【问题标题】:Closing a runnable JOptionPane关闭可运行的 JOptionPane
【发布时间】:2014-05-23 15:44:38
【问题描述】:

我有这个 Runnable 窗口:

 EventQueue.invokeLater(new Runnable(){
    @Override
    public void run() {
        op = new JOptionPane("Breaktime",JOptionPane.WARNING_MESSAGE);
        dialog = op.createDialog("Break");
        dialog.setAlwaysOnTop(true); 
        dialog.setModal(true);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);      
        dialog.setVisible(true);
     }
 });

我是否可以在这里设置一个计时器来在 1 或 2 分钟内关闭它,而不是单击“确定”按钮?

【问题讨论】:

    标签: java swing joptionpane


    【解决方案1】:

    是的,诀窍是在调用 setVisible 之前启动 Timer...

    public class AutoClose02 {
    
        public static void main(String[] args) {
            new AutoClose02();
        }
    
        private Timer timer;
        private JLabel label;
        private JFrame frame;
    
        public AutoClose02() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JOptionPane op = new JOptionPane("Breaktime", JOptionPane.WARNING_MESSAGE);
                    final JDialog dialog = op.createDialog("Break");
                    dialog.setAlwaysOnTop(true);
                    dialog.setModal(true);
                    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    
                    // Wait for 1 minute...
                    timer = new Timer(60 * 1000, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            dialog.dispose();
                        }
                    });
                    timer.setRepeats(false);
                    // You could use a WindowListener to start this
                    timer.start();
    
                    dialog.setVisible(true);
                }
            }
            );
        }
    
    }
    

    【讨论】:

    • 我应该关闭定时器吗?
    • 对不起,没听懂
    • 60 * 1000 = 1min 对,2mins 120 * 1000 怎么样?
    • 是的,1 秒 = 1000 毫秒,1 分钟 = 60 秒 = 60000 毫秒等等……你也可以使用 2 * 60 * 1000
    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 2014-04-06
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多