如何在非事件分派线程中间提示确认对话框

如何在非事件分派线程中间提示确认对话框

问题描述:

我有以下fun,将由非事件分派线程执行.在线程中间,我想要一个

I have the following fun which will be executed by non event dispatching thread. In the middle of thread, I want a

  1. 弹出确认框.线程暂停其执行.
  2. 用户做出选择.
  3. 线程将获得选择并继续执行.

但是,我发现以线程安全方式进行操作并不容易,因为对话框应该由事件分派线程显示.我尝试

However, I find out it is not easy to do it in thread safety way, as dialog box should be shown by event dispatching thread. I try

public int fun()
{
    // The following code will be executed by non event dispatching thread.
    final int choice;
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            // Error.
            choice = JOptionPane.showConfirmDialog(SaveToCloudJDialog.this, message, title, JOptionPane.YES_NO_OPTION);
        }            
    });
    return choice;
}

这当然是不可行的,因为choice是最终的,而且我无法将对话框返回的值分配给它.

Of course this won't work as choice is final, and I cannot assign the returned value from dialog to it.

实现以上三个目标的正确方法是什么?

What is the correct way to achieve the above 3 objectives?

您是否尝试过:

public int fun()
{
    // The following code will be executed by non event dispatching thread.
    final int[] choice = new int[1];
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            // Error.
            choice[0] = JOptionPane.showConfirmDialog(SaveToCloudJDialog.this, message, title, JOptionPane.YES_NO_OPTION);
        }            
    });
    return choice[0];
}