Search code examples
javaswingjoptionpane

JOptionPane.showMessageDialog Query?


This is the Scenario.

I have Code which intiates a Alram when an error is encountered.

AudioAlarm t = new AudioAlarm(song);
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Awake");
    t.start();
    setRunnung(true);
    JOptionPane.showMessageDialog(null, "Alarm ...", "Alarm", JOptionPane.OK_OPTION);
    AudioAlarm.setLoop(false);
    System.out.println("Alarm Acknowledged ...");

I would like to re-design this logic in this manner,

If the Alarm is unacknowledged by the user over a period of time say 2 min, it turn off and message msg dialog should disappear.

How can I Obtain this?

I am able to Stop the Alram, but unable to dispose the dialog without the user pressing "OK"


Solution

  • To do what you want, you should:

    • Create a JOptionPane instance using one of its constructors
    • Call createDialog on this option pane to get a dialog containing this option pane
    • Use a javax.swing.Timer instance in order to fire an action event after 2 minutes
    • add an action listener to this timer which would close the dialog containing the option pane
    • show the dialog containing the option pane.