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

Che*_*eng 5 java swing multithreading event-dispatch-thread

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

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

但是,我发现以线程安全方式执行它并不容易,因为对话框应该由事件调度线程显示.我试试

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;
}
Run Code Online (Sandbox Code Playgroud)

当然这不会choice是最终的,我不能将对话框的返回值分配给它.

实现上述3个目标的正确方法是什么?

Rek*_*kin 5

你有没有尝试过:

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];
}
Run Code Online (Sandbox Code Playgroud)