gpt4 book ai didi

java - 使用计时器自动关闭 JOptionPane.showconfirmDialog

转载 作者:行者123 更新时间:2023-11-30 08:12:48 25 4
gpt4 key购买 nike

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

我尝试了下面的示例代码。它正在部分工作。但问题是我无法模拟是/否选项。在任何情况下,它都会使用 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)

关于java - 使用计时器自动关闭 JOptionPane.showconfirmDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30251877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com