Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

java - Closing 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 that I can have a timer here to close this within 1 or 2 minutes instead of clicking the OK button?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, the trick would be to get the Timer started before you call 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);
            }
        }
        );
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...