Pong with the Java 2D API

I’m planning on using the Java 2D API for a project this summer, but I need to get familiarized first. In the previous post I covered Pong on a the C32 microcontroller. Here I’ll look at a desktop implementation using AWT.

A great starting point is this zetcode tutorial on game programming. The author covers a series of classic arcade games. I used their code to figure out how to initialize the Swing JPanel and handle keyboard input.

Here’s my implementation:

Player 1: Q, A
Player 2: Up, Down
Pause: Space
Restart: Esc

The collision detection code is almost exactly the same as the C version. This version is a little more robust in that it supports arbitrary window sizes, paddle lengths/widths/speeds, and ball velocities. The only real trouble spots were devising a scheme to handle two keys being held down simultaneously and repainting the frame at the correct times. For more fun, consider modifying this version to change the X and Y speeds of the ball based on paddle velocity or collision position.

Here’s the playable jar file and the Eclipse project with the source.


Helpful links

One Reply to “Pong with the Java 2D API”

Leave a Reply

Your email address will not be published. Required fields are marked *