java – 关闭一个可运行的JOptionPane

我有这个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分钟内关闭它而不是单击确定按钮吗?

解决方法:

是的,诀窍是在调用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);
            }
        }
        );
    }

}
上一篇:java – JoptionPane ShowConfirmDialog


下一篇:java – JOptionPane.showMessageDialog()显示但没有任何消息?