2011-08-24 89 views
1

我需要一些关于使用NetBeans开发的Java GUI的帮助。我想要用户点击一个按钮退出应用程序的功能 。我不想立即退出,而是想弹出一条消息,说:“您的工作已提交,并且此窗口将在10秒内关闭”。并且可能显示从10倒数到0.如何在x秒内关闭Java GUI应用程序?

+7

是否有一个原因以外骚扰用户? – Jeremy

+0

我看了下面的代码:long test = System.currentTimeMillis(); if(test> =(pastTime + 15 * 1000)){//乘以1000得到毫秒 doSomething(); } – RnD

+1

想到javax.swing.Timer(并且在类似情况下对我来说运行良好)。你有什么尝试?编辑:不要使用你的System.currentTimeMillis方法。再次使用[Swing Timer](http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html)。 –

回答

2

下面是该代码:(在 http://www.coderanch.com/t/341814/GUI/java/JOptionPane-Timeout感谢柯卫)

# //file CustomDialog.java  
# import javax.swing.*; 
# import java.awt.*; 
# import java.awt.event.*; 
#  
# class CustomDialog extends JDialog implements ActionListener,Runnable{ 
#  
# private JButton jButton_Yes = null; 
# private JButton jButton_NO = null; 
# private boolean OK = false; 
# private Thread thread = null; 
# private int seconds = 0; 
# private final int max = 30;//max number of seconds 
#  
# public CustomDialog(Frame frame){ 
# super(frame,true);//modal 
# setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 
#  
# Box hBox = Box.createHorizontalBox(); 
#  
# jButton_Yes = new JButton("Yes"); 
# jButton_Yes.addActionListener(this); 
#  
# jButton_NO = new JButton("NO"); 
# jButton_NO.addActionListener(this); 
#  
# JLabel jLabel = new JLabel("How are you?"); 
#  
# Container cont = getContentPane(); 
# cont.setLayout(new BoxLayout(cont,BoxLayout.Y_AXIS)); 
# cont.add(jLabel); 
# hBox.add(Box.createGlue()); 
# hBox.add(jButton_Yes); 
# hBox.add(jButton_NO); 
# cont.add(hBox); 
#  
# pack(); 
# thread = new Thread(this); 
# thread.start(); 
# setVisible(true); 
# } 
#  
# public void actionPerformed(ActionEvent e){ 
# if (e.getSource()==jButton_Yes) 
# OK = true; 
# if (e.getSource()==jButton_NO) 
# OK = false; 
# setVisible(false); 
# } 
#  
# public void run(){ 
# while(seconds < max){ 
# seconds++; 
# setTitle("OK? "+seconds); 
# try{ 
# Thread.sleep(1000); 
# }catch (InterruptedException exc){ 
# }; 
# } 
# setVisible(false); 
# } 
#  
# public boolean isOk(){return OK;} 
#  
# public static void main(String[] args){//testing 
# CustomDialog cd = new CustomDialog(new JFrame()); 
# System.out.println(cd.isOk()); 
# cd = null; 
# System.exit(0); 
# } 
#  
# }//end 
1

有关如何实现Java对话的信息,请参阅教程How to Make Dialogs。如果您想在关闭应用程序之前执行一些任务,则可以在对话窗口中显示progress