Java – close a runnable joptionpane

I have this runnable window:

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);
     }
 });

Is it possible for me to have a timer here to turn it off in 1 or 2 minutes instead of clicking the OK button?

Solution

Yes, the trick is to start the timer before calling setvisible

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);
            }
        }
        );
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>