开发者

How to display frames per second in an Java Applet in Eclipse?

This is a simple bouncing ball and i would to be able to display the the FPS while the program is running

impor开发者_运维问答t 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();
   }
}

Thanks Lochy


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);
}

BTW, your code is not thread-safe: as paint() is invoked from the Event Dispatch Thread, and run() in a thread you started, the methods should synchronize access to shared state (the fields of BallApplet).

Also note that paint() will be invoked if a part of the window that was previously occluded by another window must be repainted. The above code will count that as a "frame". If you don't want that, you shouldn't trigger drawing using repaint().


You have one frame appearing every 20 milliseconds, or 50 frames per second. However, due to the nature of Thread.sleep(), it might be shorter or longer than 20 milliseconds in between each frame.

If you want to display 50 fps, look into JLabel.

/e1
Why do you have two methods (start() and start1()) which do exactly the same thing?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜