2014-12-27 100 views
0

我試圖讓這個圖形用戶界面有這些單詞從屏幕的頂部落下,我在我的構造函數中有以下代碼,其中單詞每100毫秒移動一個單元。但是,當我運行該程序時,一旦我開始並且不在屏幕的頂部,單詞將出現在400處。我想有一個具體的方法可以連續更新我的y值?謝謝!下降的單詞沒有給出預期的結果

while(y <= 400){ 
     y++; 
     repaint(); 
     try { 
      TimeUnit.MILLISECONDS.sleep(100); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(Painting.class.getName()).log(Level.SEVERE, null, ex); 
     } 
} 
+0

用了什麼價值'y'開始?這是你的代碼片段中缺少的。 – usr2564301 2014-12-27 18:12:34

+0

我從y = 20開始,這是一種隨意的 – user19164 2014-12-27 19:05:32

+0

_不要在EDT上睡覺; _do_參見[* Swing中的併發*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)和[*如何使用Swing定時器*](http://docs.oracle.com/ JavaSE的/教程/ uiswing /雜項/ timer.html)。 – trashgod 2014-12-27 23:19:40

回答

0

睡你的線程是不採取預期結果的最佳做法,使用Timer代替:

Timer timer = new Timer(100, new ActionListener() { //100 is the delay time between each interval 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      repaint(); 
      y ++; 
      if (y > 400) { 
       ((Timer) e.getSource()).stop(); 
      } 
     } 
    }); 
    timer.start(); 
相關問題