CHEBURASHKA
CHEBURASHKA

Reputation: 1713

How to auto click OK of JOptionPane

I have a JOptionPane. If a user does not click it in 10 minutes, then the JOptionPane should auto click OK.

How can I do this?

Upvotes: 0

Views: 1013

Answers (1)

Joel Christophel
Joel Christophel

Reputation: 2663

First, create a JDialog from a JOptionPane object. Then, create a timer to run for 10 minutes (600,000 milliseconds), and dispose the dialog once it has finished. Then, retrieve the chosen value from your JOptionPane object, making sure to account for an uninitialized value if the dialog was disposed by your timer.

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;

public class Tester {
    public static void main(String[] args) {
        final JOptionPane pane = new JOptionPane("Hello world?", JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        final JDialog dialog = pane.createDialog(null, "Hello world");
        Timer timer = new Timer(600000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                dialog.dispose();
            }

        });
        timer.start();
        dialog.setVisible(true);
        dialog.dispose();
        Integer choice = (Integer) (pane.getValue() == JOptionPane.UNINITIALIZED_VALUE ? JOptionPane.OK_OPTION : pane.getValue());
    }
}

Upvotes: 2

Related Questions