簡體   English   中英

動作前如何設置計時器?

[英]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);
     }
 }

我如何在下面的代碼中設置計時器..我標記了我想放置一個小計時器的位置..任何想法都可以做到這一點? 我的目標是稍等一會,直到服務器准備好向我發送數據為止。以便我可以接收正確的數據!

最簡單的解決方案是使用Thread.sleep(long milliseconds)方法。 如果當前線程由於某種原因被中斷,則拋出InterruptedException 用法示例如下:

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

重要說明 :注意,Swing線程中的Thread.sleep(int milliseconds)將使GUI凍結! 您應該將jButton1ActionPerformed()方法ActionPerformed中的所有代碼移到另一個線程上運行。

感謝@Stony Zhang

您可以使用insert Thread.sleep(2000) ,這會使您的應用程序暫停2,000毫秒(即2秒)。 請注意,這必須出現在try塊中,該try塊緩存一個InterruptedException ,如果另一個線程在休眠時中斷該線程,則該異常將被拋出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM