Java Reference
In-Depth Information
The remainder of the code (not shown) builds the Stage and places the
ImageView
object in the scene graph. Once the application is compiled and executed, it shows an
image of the letter when the corresponding letter is pressed on the keyboard, as shown
in the next screenshot:
How it works...
This recipe demonstrates the techniques involved in loading multiple images for display and
programmatic manipulation. Let's examine how it's done:
F
Image file format
—part of what makes this technique easier is that all images are of
the same format. This reduces the size of the code by assuming that all images are
of one type (PNG format here).
F
Image location
—another important trick that makes this approach work is a uniform
location for all images. The images in this recipe are all located in the same directory,
source-code/src/alphabet/images
. The JavaFX packager will automatically
add the images in the generated JAR file and thus be available from the classpath for
easy access.
F
The alphabet sequence
—lastly, using a natural series as the naming strategy
for the images makes it easy (not necessary) to load the images quickly. In
the recipe, the first portion of the code declares a sequence of strings, named
alphabet:String[]
. This
Sequence
instance contains all of the letters of the
alphabet. Recall that each image is named using a single letter of the alphabet
(that is,
A.png
,
B.png
, and so on). This sequence can be mapped directly to the
collection of image files representing the alphabet.
F
Loading the images
—next, the code does the following:
It declares variable
images[]
as a Sequence, used to store
Image
instances that are created when the image files are loaded.
The
code loops through the
alphabet
sequence using the
letter
variable. For each
letter
in the sequence, the code creates an
Image
instance for the PNG file that matches the current value
of
letter
, using the expression
url: "{__DIR__}images/
{letter}.png"
. Then, the Image object is inserted in the
sequence
images[]


