/**
* -- 倒计时提示弹窗
*
* @param ParentComponent -- 弹窗父窗体(没有父窗体设置为 null)
* @param icon -- 图标
* @param title -- 标题
* @param message -- 提示消息
* @param countdown -- 倒计时布尔值(true -- 开启倒计时,false -- 关闭倒计时)
* @param ms -- 倒计时时长(毫秒)
* @param exitsytem -- 退出进程布尔值(true -- 调用系统的System.exit(0)方法,退出整个进程,false -- 关闭当前提示窗口)
*/
public static void showMessageDialog_CountDown(JFrame ParentComponent, final int icon,final String title,final String message ,boolean countdown, final int ms,boolean exitsytem) {
if(ParentComponent != null) {// -- 判断传入父窗体是否为空
// -- 设置父类窗体禁用
ParentComponent.setEnabled(false);
ParentComponent.setModalExclusionType(ModalExclusionType.NO_EXCLUDE);
}else {// -- 如果为空,创建父类窗体
// -- 窗体
JFrame f = new JFrame("弹窗父窗体");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// -- 窗体表示
f.pack();
f.setAlwaysOnTop(true); // -- 窗口在最前端显示
f.setLocationRelativeTo(null); // -- JFrame窗口居中显示
//f.setVisible(true); // -- 显示窗体
}
// -- 换算成秒
final int count = ms / 1000;
JButton okBtn = new JButton();
String okBtnText = "确定" + "(" + count + "s)" ;
if(countdown) {
okBtn.setText(okBtnText);
}else {
okBtn.setText("确定");
}
final Object[] options = {okBtn };
final int[] optionIcon = {icon };
final JOptionPane op = new JOptionPane(message, optionIcon[0], JOptionPane.DEFAULT_OPTION, null, options);
final JDialog dialog = op.createDialog(title);
// -- 设置确定按钮单击监听
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// -- 关闭对话框
dialog.setVisible(false);
dialog.dispose();
if(exitsytem)System.exit(0);
}
});
// -- 倒计时布尔值为 true 时,开启到计时
if(countdown && ( count >= 0 )) {
// 创建一个新计时器
Timer timer = new Timer();
// X秒后执行该任务
timer.schedule(new TimerTask() {
public void run() {
for (int i = count - 1; i >= 0; i--) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("toWait(,1000);");
String okBtnText = "确定" + "(" + i + "s)";
okBtn.setText(okBtnText);
// -- 更新UI
okBtn.updateUI();
}
dialog.setVisible(false);
dialog.dispose();
if(exitsytem)System.exit(0);
}
}, 10);
}
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.setModal(true);
dialog.setVisible(true);
}
使用方法:
showMessageDialog_CountDown(
null,
JOptionPane.WARNING_MESSAGE,
“警告”,
“测试” ,
true,
15*1000,
true);