3

I want to create a JOptionPane.showConfirmDialog with a timer. And the default option will be Exit. But if i click on Yes option it should continue the work , and if I click No Option it should exit. If I don't click on any option it should automatically exit from the code.

I tried the below sample code. It is partially working. But the problem is I cannot simulate the Yes/No Option. In any case it is exiting from the code with the YES option.

Although this code is taken from one of the thread, but there the implementation is different. I just modified the code according to my need. Please find the below code:

public class TestProgress {

public static void main(String[] args) {
    final JOptionPane msg = new JOptionPane("Database Already Exist. Do you want to continue...?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
    final JDialog dlg = msg.createDialog("Select Yes or No");
    final int n = msg.YES_NO_OPTION;
    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              Thread.sleep(5000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }

            if(msg.YES_OPTION==n){
                System.out.println("Continue the work.. "); // should not exit
            }
            else if(msg.NO_OPTION==n)
                dlg.setVisible(false);
                System.exit(1);
            }


        }).start();
        dlg.setVisible(true);
        System.out.println("Outside code.");
    }
}  

What else do I need to do, to make it work correctly?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Shubhro
  • 73
  • 2
  • 11
  • You mean something like [this](http://stackoverflow.com/questions/22979504/closing-a-runnable-joptionpane/22979571#22979571) for example? – MadProgrammer May 15 '15 at 05:29
  • 1
    While we're on the subject, you code makes no sense. `JOptionPane` presents a modal dialog. This means that once you call `setVisible`, the code execution will block until the dialog is closed. You should inspect the result result from `JOptionPane.showMessageDialog` or `JOptionPane.showConfirmationDialog` and make you choices then – MadProgrammer May 15 '15 at 05:32
  • @MadProgrammer actually it's possible to add a WindowListener or WindowFocusListener to the JOPtionPane's dialog to start the Timer and close after some time. – StanislavL May 15 '15 at 06:19
  • @StanislavL But in this case, why bother? The OP isn't closing the dialog themselves after some time out, there just "inspecting" the values – MadProgrammer May 15 '15 at 06:24

2 Answers2

2

The autoclosing dialog of JOptionPane

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class TestProgress {

    public static void main(String[] args) {


        final JOptionPane msg = new JOptionPane("Database Already Exist. Do you want to continue...?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        final JDialog dlg = msg.createDialog("Select Yes or No");
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dlg.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent e) {
                super.componentShown(e);
                final Timer t = new Timer(5000,new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dlg.setVisible(false);
                    }
                });
                t.start();
            }
        });
        dlg.setVisible(true);
        System.out.println("Outside code.");
    }

}  

UPDATE:

Use extended constructor where you can pass initial option and specify NO as default

JOptionPane(Object message, int messageType, int optionType,
                   Icon icon, Object[] options, Object initialValue)
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • the code which you have mentioned is not the one which i want. It is not exiting by default and even if i click NO option also. I want something where it will ask for YES/NO option and upon clicking on YES option it should continue the other work(come out from the IF/ELSE block. If i click on NO option, it should exit there only, (System.exit(int). – Shubhro May 15 '15 at 10:44
  • It's just an example. Use it to add all the logic you need. – StanislavL May 15 '15 at 10:54
  • If i add my code inside this part public void actionPerformed(ActionEvent e) { dlg.setVisible(false); } it is not working, i dont know exactly where i have to put my logic. I even tried to fetch the value of the Yes/NO button, but I am not getting that too. Please show me a sample with the above example which you have show, – Shubhro May 18 '15 at 06:26
1

a completed answer for this question.

public final static boolean showConfirmDialogWithTimeout(Object params, String title, int timeout_ms) {
    final JOptionPane msg = new JOptionPane(params, JOptionPane.WARNING_MESSAGE, JOptionPane.CANCEL_OPTION);
    final JDialog dlg = msg.createDialog(title);

    msg.setInitialSelectionValue(JOptionPane.OK_OPTION);
    dlg.setAlwaysOnTop(true);
    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dlg.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent e) {
            super.componentShown(e);
            final Timer t = new Timer(timeout_ms, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dlg.setVisible(false);
                }

            });
            t.start();
        }
    });
    dlg.setVisible(true);

    Object selectedvalue = msg.getValue();
    if (selectedvalue.equals(JOptionPane.CANCEL_OPTION)) {
        return false;
    } else {
        return true;
    }
}

    // example usage
    String message = "The earth will explode in 10 seconds. Select CANCEL if you won't.";
    JLabel lbmsg = new JLabel(message);
    boolean result = showConfirmDialogWithTimeout(lbmsg, "Shutdown Warning", 10 * 1000);

    if (result == false) {
        Utils.showMessage(message + " cancel is selected");
    }
    else {
        Utils.showMessage(message + " timeout or okay is selected");
    }