Search code examples
javamultithreadingswingjoptionpane

How to run two JOptionPane's with threads


I have to set two Dialogs and i want to Stop the first one and then start the second. Can anyone please help me to fix it

JOptionPane msg = new JOptionPane("your score is:  " + getScore(), JOptionPane.INFORMATION_MESSAGE);
        final JDialog dlg = msg.createDialog("Game Over");
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);



     new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              Thread.sleep(3000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            dlg.dispose();

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

the second Dialog would be the same like

JOptionPane message = new JOptionPane("Highscore:  " + getHighscore(), JOptionPane.INFORMATION_MESSAGE);
        final JDialog dialog = message.createDialog("Game Over");
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

now i want to start this Dialog after the first will be closed.


Solution

  • Recommendations:

    1. For the sake of Swing thread safety, use a Swing Timer rather than directly using a background thread.
    2. Make it a non-repeating timer.
    3. Inside the timer's ActionListener, close/dispose of the current dialog and open the 2nd.

    e.g., (code not tested)

    final JDialog myModalDialog = ....;
    final JDialog mySecondDialog = ....;
    int timerDelay = 3000;
    Timer timer = new Timer(timerDelay, e -> {
        myModalDialog.dispose();
        mySecondDialog.setVisible(true);
    });
    timer.setRepeats(false);
    timer.start();
    myModalDialog.setVisible(true);
    

    Alternatively: use a single dialog and swap views using a CardLayout tutorial