开发者

How to close a Java GUI application in x seconds?

开发者 https://www.devze.com 2023-03-30 12:16 出处:网络
I need some help regarding the Java GUI I developed using NetBeans. I want the functionality where the user clicks on a button to exit the application. Instead of immediately exiting, I开发者_开发问答

I need some help regarding the Java GUI I developed using NetBeans. I want the functionality where the user clicks on a button to exit the application. Instead of immediately exiting, I开发者_开发问答 would like a message to pop up saying "Your job was submitted and this window will close in 10s". And maybe show a count down from 10 to 0.


JOptionTest is an example that uses javax.swing.Timer.


Here is the code for that: (Thanks to Ko Wey at 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  


For information on how to implement Java dialogue check out the tutorial How to Make Dialogs. If you want to perform some task before closing the app, you could display progress in your dialogue window.

0

精彩评论

暂无评论...
验证码 换一张
取 消