日期:2014-05-20  浏览次数:20765 次

用JOptionPane生成一个对话框,
生成之后,要点击确定按钮才会关闭此信息提示对话框,
我想在想让它在5秒之后自动关闭该怎么写下面的代码呢?

------解决方案--------------------
final JOptionPane options = ...;
final JDialog  dialog = options.createDialog(...);
final javax.swing.Timer timer = new javax.swing.Timer(5000, // 5s delay
                                  new ActionListener(){
                                       public void actionPerformed(ActionEvent e){
                                           dialog.dispose();
                                       }
                                  });
dialog.addComponentListener(new ComponentAdapter(){
         public void componentShown(ComponentEvent e){
              timer.start();
         }
    });

------解决方案--------------------

//定义一个倒计时自动消失的窗口类
public class TimeDialog {

private String message = null;
private int secends = 0;
private JLabel label = new JLabel();
private JDialog dialog = null;

public void showDialog(JFrame father, String message, int sec) {
this.message = message;
secends = sec;
label.setText(message+"  本窗口 "+secends+" 秒后关闭自动");
ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
dialog = new JDialog(father, "提示信息", true);
dialog.add(label);
s.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

TimeDialog.this.secends--;
if(TimeDialog.this.secends == 0) {
TimeDialog.this.dialog.dispose();
}else {
label.setText(TimeDialog.this.message+"  本窗口 "+secends+" 秒后关闭自动");
}
}
}, 1, 1, TimeUnit.SECONDS);
dialog.pack();
dialog.setLocationRelativeTo(father);
dialog.setVisible(true);
}

}


//在你的程序中,用下面的语句弹出一个倒计时窗口
TimeDialog d = new TimeDialog();
d.showDialog(MyFrame.this, "你好", 5);// MyFrame是程序主窗口类,弹出的对话框5秒后消失