Subscribe to Dogstopper's Code Mania        RSS Feed
***** 1 Votes

Frame Rate in Java

Icon Leave Comment
Well, as this is my first entry in the Game Programming section, I think I should link my introductory tutorial. http://www.dreaminco...topic143744.htm

Anyway, this section is dedicated to aspects of several languages that should be taken advantage of. In this entry, I will show you the most basic method of how to establish a frame rate in Java.

Firstly, how to calculate? Say, we want 70 FPS. Since there are 1000 milliseconds in a second, we divide 100 by the frame rate to get the number of milliseconds on each frame. 1000/70 = ~14.28 ms...

Well, that's a little fast, so let's round it up to 15, about 66 FPS. Now, we use the javax.swing.Timer class to call a certain method every specified number of milliseconds. The syntax looks like this: Timer time = new Timer(<number_of_millies>, <handling_method>);. An important note is that it requires an ActionListener, and it calls actionPerformed().

Let's see how to implement it:
class Ball {
	private int x=0, y=0;
	private int xDir=1, yDir=1;
	public void move() {
		x += xDir;
		y += yDir;

	public void draw(Graphics g) {
		g.fillOval(x, y, 5, 5); // x, y, width, height

Well, this class represents a ball, obviously incomplete and you can add more functionality.
Now, for the JPanel doing the drawing...
public class BallPanel extends JPanel implements ActionListener {
	private Ball myBall;	 

	public BallPanel() {
		//... set width, height, w/e  
		myBall = new Ball();
		// Set up a Timer for 15 milliseconds to call actionListener
		Timer time = new Timer(15, this);
	public void actionPerformed(ActionEvent e) {
		 // Move the ball

	// Controls the painting
	public void paintComponent(Graphics g) {
		// Paint the background
	g.fillRect(0, 0, width, height);
		// Draw the ball
		// makes sure monitors are up to date on *NIX systems

That's the skeleton code, and obviously, you will need to add the width, height, key listeners, and whatever else you need to make it work fully.

Thanks for reading!
~Stephen Schwahn

0 Comments On This Entry


August 2017

20 21 2223242526

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)