2011-07-31 42 views
2

這是一個簡單的反彈球 ,我會以能夠顯示的FPS程序運行如何在Eclipse中的Java Applet中每秒顯示幀數?

import java.awt.*; 
import java.applet.Applet; 
import java.awt.Color; 
import java.awt.Graphics; 

public class BallApplet extends Applet implements Runnable { 
    private int ballX, ballY; 
    private final int radius = 50; 

    public void start1() { 
     Thread th = new Thread(this); 
     th.start(); 
    } 

    @Override 
    public void run() { 
     int dx = 2; 
     int dy = 2; 
     int speed = 2; 
     // This will reduce the load the applet has on the runtime 
     // system.. 

     Thread.currentThread().setPriority(… 
     while (true) { 
     ballX += dx; 
     ballY += dy; 
     repaint(); 
     if (ballX + radius > getWidth()) 
      dx = -speed; 
     else if (ballX < 0) 
      dx = speed; 
     if (ballY + radius > getHeight()) 
      dy = -speed; 
     else if (ballY < 0) 
      dy = speed; 
     try { 
      Thread.sleep(20); 
     } catch (InterruptedException ie) { 
     } 
     } 
    } 

    // set up BallApplet object 
    public void init() { 
     ballX = 0; 
     ballY = getHeight()/2; 
    } 

    // Drawing instructions… 
    public void paint(Graphics g) { 
     super.paint(g); 
     g.setColor(Color.red); 
     g.fillOval(ballX - radius, ballY - radius, 2 * radius, 2 * radius); 
    } 

    // The standard Applet 「GO」 function… 
    public void start() { 
     Thread th = new Thread(this); 
     th.start(); 
    } 
} 

由於洛希

+1

請格式化您的代碼,謝謝! – home

回答

0

而你必須出現每20毫秒一幀,或50幀每秒。但是,由於Thread.sleep()的性質,它可能比每幀之間的時間短或長於20毫秒。

如果你想顯示50幀,看看JLabel

/e1
爲什麼你有兩種方法(start()start1())完全相同的東西?

1
long nextSecond = System.currentTimeMillis() + 1000; 
int frameInLastSecond = 0; 
int framesInCurrentSecond = 0; 


public void paint() { 
    // ... other drawing code goes here 

    long currentTime = System.currentTimeMillis(); 
    if (currentTime > nextSecond) { 
     nextSecond += 1000; 
     frameInLastSecond = framesInCurrentSecond; 
     framesInCurrentSecond = 0; 
    } 
    framesInCurrentSecond++; 

    g.drawString(framesInLastSecond + " fps", 20, 20); 
} 

順便說一句,你的代碼是不是線程安全的:作爲paint()從事件指派線程在你開始,這些方法應該同步訪問共享狀態(的BallApplet領域)的線程上調用,並run()

還要注意,如果先前由另一窗口遮擋的窗口的一部分必須重新繪製paint()將被調用。上面的代碼會將其視爲一個「框架」。如果你不想這樣做,你不應該使用repaint()來觸發繪圖。