2011-06-07 61 views
0

我有一個2D遊戲,整個結構是完全編碼,除了圖形。我只是更新一個包含50個圖像的Graphic的JFrame的單個組件。每幀圖像都在不同的位置,因此需要更新刷新率。如何設置刷新率的JFrame?

爲了繪製,我重寫了paintComponent()方法,所以我真正需要做的是每40毫秒重新繪製一次組件(它再次只是一個圖形)。

如何設置25FPS的JFrame?

+1

我猜你不想和每秒25幀更新一個JFrame,但它的一些內容。你使用Java3D嗎?你使用OpenGL嗎?什麼是顯示面板的父類(jpanel,widget,...)? – Hyperboreus 2011-06-07 04:58:53

+0

這是一個廣泛的問題,如前所述,我認爲是無法回答的。 – 2011-06-07 05:02:13

+0

@Hovercraft充滿鰻魚:現在應該足夠具體。告訴我是否需要更多細節。 – Will 2011-06-07 05:06:28

回答

2

AnimationTest使用javax.swing.Timer。 40毫秒的時間會產生25赫茲的速率。

private final Timer timer = new Timer(40, this); 

附錄:計時器的ActionListener響應通過調用repaint(),隨後調用你的覆蓋paintComponent()方法

@Override 
public void actionPerformed(ActionEvent e) { 
    this.repaint(); 
} 
+0

javax.swing.Timer +1 – mKorbel 2011-06-07 05:56:06

+0

這只是添加到公共靜態void main方法的結尾? – Will 2011-06-07 06:18:15

+0

@ will:是的,只要你在[event dispatch thread](http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)上,通常在'setVisible()'後面。 – trashgod 2011-06-07 13:51:53

4

這是一個壞主意,刷新一個JFrame。它是Swing中爲數不多的重要組件之一。最好的辦法是

  • 確定包含動畫
  • 創建擴展JPanel類的面板。即GamePane擴展JPanel
  • 重寫paintComponent(無S)

你的標題有誤導之嫌,你做了正確的事情。

    在你的JFrame
  • 創建一個亞軍類

/** Thread running the animation. */ 
private class Runner extends Thread 
{ 
    /** Wether or not thread should stop. */ 
    private boolean shouldStop = false; 
    /** Pause or resume. */ 
    private boolean pause = false; 

    /** Invoke to stop animation. */ 
    public void shouldStop() { 
     this.shouldStop = true; 
    }//met 

    /** Invoke to pause. */ 
    public void pauseGame() { pause = true; }//met 
    /** Invoke to resume. */ 
    public void resumeGame() { pause = false; }//met 

    /** Main runner method : sleeps and invokes engine.play(). 
    * @see Engine#play */ 
    public void run() 
    { 
     while(!shouldStop) 
     { 
      try { 
       Thread.sleep(6); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }//catch 
      if(!pause) 
      { 
       engine.play(); 
            gamePane.repaint(); 

      }//if 
     }//while 
    }//met 

    /** Wether or not we are paused. */ 
    public boolean isPaused() { 
     return pause; 
    }//met 
}//class Runner (inner) 

動畫會順利得多。並使用MVC和事件刷新UI的其他部分。

問候, 斯特凡