jolyTimePopCorn
jolyTimePopCorn

Reputation: 23

how to set timer before doing a action?

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {      
     char[] pass = pass1.getPassword();  
     String passString = new String(pass);
     String l = "1;"+jTextField1.getText()+"/"+passString+"/"; 

     try{
         a.connection_send(l); 
         \\HEREEE :  I want to wait here 2 secondes before continue and doing a.connection_get() 
         loginInfo = a.connection_get();


         if(Integer.parseInt(loginInfo) == 1) {
            home_page a = new home_page();
            a.setBounds(500, 200, 470, 330); 
         } else { 
            JOptionPane.showMessageDialog(null, "Wrong UserName or Password", "Alert !", JOptionPane.WARNING_MESSAGE);
            jTextField1.setText("");
            pass1.setText("");
         }
     } catch(Exception e) { 
         JOptionPane.showMessageDialog(null, "You Are not connected to Server !\nPlease check Your netowrk ", "Alert !", JOptionPane.WARNING_MESSAGE);
     }
 }

How can i set a timer in the below code .. i marked where i want to place a little timer .. any idea to do that ? My objective is to wait a little bit until server is ready to send me the data .. so i can receive the proper data !

Upvotes: 0

Views: 137

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

The most simple solution is to use the Thread.sleep(long milliseconds) method. It throws an InterruptedException if the current thread is interrupted for some reason. Sample usage is as follows:

try {
  Thread.sleep(2000); //2000 milliseconds = 2 seconds
} catch (InterruptedException e) {
  e.printStackTrace();
}

IMPORTANT: Note that Thread.sleep(int milliseconds) in Swing thread will make the GUI freeze! You should move all code in the jButton1ActionPerformed() method ActionPerformed to another thread to run.

Thanks to @Stony Zhang

Upvotes: 1

drew moore
drew moore

Reputation: 32680

You can use insert Thread.sleep(2000), which causes your application to pause for 2,000 milliseconds (i.e. 2 seconds). Note that this will have to appear in a try block that caches an InterruptedException, which gets thrown if another thread interrupts this one while it is sleeping.

Upvotes: 0

Related Questions