Part 1

Opening the Table Tennis project


In this project, we will learn how to combine the graphics we used in the last project and what we know about Java classes to create our own simple video game! We will create a “Table Tennis” video game, essentially a single player version of “Pong.”

Start off by opening up the Table Tennis project. (File->Open)

Once that’s open, open up the “Ball” java file.


Creating Ball class variables


Next, add the code as shown here to create the class variables that we will need for the “Ball” class.

We first create a new static int called “DIAMETER” to control how big the ball will be. We use the keyword final here to make this variable a constant, meaning that the value cannot be edited. It is common programming practice to name final/constant variable in all caps.

The x and y variables are used to keep track of the ball’s position in the window.

The xa and ya variables are used for the speed of the ball in the x and y directions.

The “game” variable is a reference to the game itself, which we will need to have access to some important data later on.

Creating Ball constructor and paint method


Next, add the code as shown here to create the class constructor as well as the paint method to help draw it in a window.

Here our constructor is pretty simple, we just need to give it one parameter, the game the ball is a part of. We then save this reference inside the constructor.

For our paint function, we have a “Graphics2D” parameter which will be used to draw the ball. We then draw the ball using the “fillOval” function, our diameter, and the x and y coordinates.

Preparing to draw the Ball


Now let’s get ready to code the Ball to actually appear on the window. Open up the “Main” file.

Inside the “Main” file, at the very top of the class, add the code as shown.

This will create two new class variables, a “Ball” variable for the ball and an int variable for the current speed of the game.


Drawing the Ball


Still inside the “Main” file, within the “paint” function, add the code as shown to draw the ball.

Once done, go ahead and test out the code. You should see a ball appear on the screen!