Danedesta
Danedesta

Reputation: 119

Is it possible to pause current thread while JOptionPane is open?

I'm working on a game in Java, and i'm trying to pause it while JOptionPane confirm box is open. Here is the code:

window.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent event) {

            int dialogResult =  JOptionPane.showConfirmDialog (null, "Would You Like to exit this game? Your progress will not be saved!","Warning",JOptionPane.YES_NO_OPTION);
            //What should i do with this???
            try {
                Thread currentThread = Thread.currentThread();
                synchronized(currentThread) {
                    currentThread.wait();
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ////
            if(dialogResult == JOptionPane.YES_OPTION){
                exitProcedure();
            }
            else {
                if(dialogResult == JOptionPane.NO_OPTION || dialogResult == JOptionPane.CLOSED_OPTION) {

                    Thread currentThread = Thread.currentThread();
                    synchronized(currentThread) {

                        currentThread.notify();
                    }

                }
            }

        }
    });

Is this the right way to do this? What should I do differently to make it work?

Upvotes: 0

Views: 397

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44960

The Swing events are handled in the Event Dispatcher Thread and you don't want to pause this thread in any way. It handles all the UI operations like repaint so any pause will make your application unresponsive.

You would have to obtain the reference to the thread which is running the background logic and then pause it. It's most likely not Thread.currentThread() although you have not provided the complete source code. You can check the thread type with SwingUtils.isEventDispatchThread() method.

Upvotes: 1

Related Questions