2016-03-26 29 views

回答

2

我認爲這個問題正在接受投了反對票,因爲:

  • 目前還不清楚這個問題的背景是什麼,以及/或者你正在嘗試做
  • 您還沒有上市什麼你已經張貼
  • 谷歌之前嘗試或許可以回答你的問題

但樂於助人的精神:

我諮詢了谷歌上找到了Java這個資源擺動定時器:http://supportweb.cs.bham.ac.uk/documentation/java/tutorial/uiswing/misc/timer.html

我不是Java專家,但我會建議嘗試:

for (int j = 0; j < 0; i++) { 
    System.out.println(j); 
    timer = new Timer(ONE_SECOND, new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
      //...Whatever you are trying too do (ie. update progress bar) 
       if (/* What you are waiting for */) { 
        try { 
         Thread.sleep(1000); 
         } catch (Exception e) { 
        // 
        } 
       } 
     }  
    }); 
    } 
2

您的for循環有兩個語法問題

for (int j = 0; j < 0; i++) { 

您正在比較j < 0(並且假設j的初始值爲0,則不會輸入您的循環),並且您正在增加i而不是j。假設您的循環打算以1秒的間隔打印09的數字,您可以使用TimerActionListener這樣做。從監聽器開始,初始化一個計數器,並保持對Timer的本地引用(以便監聽器可以停止計時器)。類似於

static class MyListener implements ActionListener { 
    int n = 0; 
    Timer t; 

    public void setTimer(Timer t) { 
     this.t = t; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (n < 10) { 
      System.out.println(n++); 
     } else { 
      // Stop the Timer 
      t.stop(); 
     } 
    } 
} 

接下來,我們需要創建一個Timer;初始化Listenerstart(等待過程完成)。類似於

public static void main(String[] args) { 
    MyListener mm = new MyListener(); 
    try { 
     SwingUtilities.invokeAndWait(new Runnable() { 
      @Override 
      public void run() { 
       Timer t = new Timer(1000, mm); 
       mm.setTimer(t); 
       t.start(); 
      } 
     }); 
    } catch (InvocationTargetException | InterruptedException e) { 
     e.printStackTrace(); 
    } 
}