Citadel Game Design Club
Lesson 5: Images & Sounds
This lesson adds code to the program from Lesson 4. You will
need to have a working ball and paddle game to proceed with
this lesson.
1.) Add Resources to Your Project
First we need to add the image and sound files to our project. Go to our club website:
http://macs.citadel.edu/wittman/gameclub
Next to today's lesson on Images & Sounds, you should see the file Resources.zip. Click
on it, select "Save As" and save it to your Desktop. Then extract the zip file.
Next open your project in Java Eclipse. Drag and drop the two files in the Resources
folder you just download into your Java Eclipse directly into the src folder of your Java
project.
2.) Displaying an Image
Let's display the picture image1.jpg on our bouncing ball. First, we need to add a couple
JavaFX libraries to the top of our program.
import javafx.scene.image.*;
import javafx.scene.paint.*;
Next we load the file onto an Image variable. To display this on a JavaFX shape like a
Rectangle or Circle, we have to cast it to an ImagePattern. Add this code before you
create your circle object.
Image image = new Image("image1.jpg");
ImagePattern ip = new ImagePattern(image);
After the circle object is created, let's paint our ImagePattern onto the shape.
circle.setFill(ip);
So that you can see the image a little better, you may want to set your Circle radius a little
bigger than 15, like 50.
2.) Playing a Sound
To play a sound in JavaFX, we need to add 2 more libraries to the top of our program.
import javafx.scene.media.*;
import java.net.URL;
We first load the sound into a URL object. Then we cast it to an AudioClip so it is ready
to play.
URL sound = getClass().getResource("sound1.wav");
AudioClip clip = new AudioClip(sound.toString());
Let's play a sound every time the ball hits the paddle. Recall we added an if statement to
the Timeline that detects when the paddle intersect circle. Let's add some braces to the if
statement and play the AudioClip at normal speed (speed=1.0).
if ( paddle.getBoundsInParent().intersects(circle.getBoundsInParent()) )
dy = -dy;
clip.play(1.0);
}
Note that our code does not stop playing the clip when another bounce occurs. So you
can get an unusual echo effect if you trigger multiple bounces in a short time frame.
4.) Just for Fun
Think of a fun rectangular shape to make the paddle and paint it on top of the paddle
rectangle.
You could also look up sound files online to play when the ball hits the wall. JavaFX
supports AU and uncompressed WAV files. Unfortunately, most WAV files are
compressed so you may have to look for a sound converter.
{
© Copyright 2026 Paperzz