JOptionPane打开时是否可以暂停当前线程?

时间:2018-03-26 21:48:53

标签: java multithreading swing joptionpane

我正在使用Java开发游戏,并且在JOptionPane确认框打开时我试图暂停它。这是代码:

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();
                    }

                }
            }

        }
    });

这是正确的方法吗?我应该采取哪些不同的方式来使其发挥作用?

1 个答案:

答案 0 :(得分:1)

Swing事件在Event Dispatcher Thread中处理,您不想以任何方式暂停此线程。它处理所有UI操作,如重绘,因此任何暂停都会使您的应用程序无响应。

您必须获取对运行后台逻辑的线程的引用,然后暂停它。尽管您尚未提供完整的源代码,但它很可能不是Thread.currentThread()。您可以使用SwingUtils.isEventDispatchThread()方法检查线程类型。