我想创建一个带有计时器的JOptionPane.showConfirmDialog。默认选项是退出。但是,如果我单击“是”选项,它将继续工作,如果我单击“否选项”,则应该退出。如果我没有单击任何选项,它将自动从代码中退出。

我尝试了以下示例代码。它正在部分工作。但是问题是我无法模拟“是/否”选项。无论如何,它都是使用YES选项从代码中退出的。

尽管此代码是从线程之一中获取的,但是在实现上却有所不同。我只是根据需要修改了代码。
请找到以下代码:

public class TestProgress {

public static void main(String[] args) {
    final JOptionPane msg = new JOptionPane("Database Already Exist. Do you want to continue...?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
    final JDialog dlg = msg.createDialog("Select Yes or No");
    final int n = msg.YES_NO_OPTION;
    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              Thread.sleep(5000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }

            if(msg.YES_OPTION==n){
                System.out.println("Continue the work.. "); // should not exit
            }
            else if(msg.NO_OPTION==n)
                dlg.setVisible(false);
                System.exit(1);
            }


        }).start();
        dlg.setVisible(true);
        System.out.println("Outside code.");
    }
}

我还需要做什么才能使其正常工作?

最佳答案

JOptionPane的自动关闭对话框

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class TestProgress {

    public static void main(String[] args) {


        final JOptionPane msg = new JOptionPane("Database Already Exist. Do you want to continue...?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        final JDialog dlg = msg.createDialog("Select Yes or No");
        dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dlg.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent e) {
                super.componentShown(e);
                final Timer t = new Timer(5000,new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dlg.setVisible(false);
                    }
                });
                t.start();
            }
        });
        dlg.setVisible(true);
        System.out.println("Outside code.");
    }

}

更新:

使用扩展的构造函数,您可以在其中传递初始选项并将NO指定为默认值
JOptionPane(Object message, int messageType, int optionType,
                   Icon icon, Object[] options, Object initialValue)

09-10 07:19
查看更多