Java Reference
In-Depth Information
The drawString() methods instruct the program to display text output in the
positions defined by the coordinate parameters. The toString() method in line
21 is an example of polymorphism. As you learned in Chapter 1, polymorphism
allows a program to use the same command while obtaining different but some-
what predictable results, depending on the object that receives the command.
The toString() method is polymorphic in that the same method name is used to
refer to methods that handle many different data types, but the result is always a
String conversion. You will learn more about data type conversions in the next
chapter.
Entering Code to Draw an Image and Set
the Background Color
The final step in editing the source code is to insert the commands necessary
to display a graphic in the applet and change the background color of the window.
As shown in Figure 2-54, the edited source code will declare an Image object, use
a method named getImage() to retrieve a graphic file from the disk, use the
drawImage() method to draw the graphic in the applet window, and then use
the setBackground() method to change the color of the window.
FIGURE 2-54
The Image object will have a variable name of smile, as declared in line 22.
The Image object must be declared before its methods can be used. Java applet
images may be one of many different types of graphics including GIF, JPEG, or
PNG. In the Welcome to My Day program, the graphic is a GIF file with the file
name Smile.gif.
The getImage() method , as shown in line 23, is used to load images into
an applet. The getImage() method creates and returns an Image object that rep-
resents the loaded image. The getImage() method uses a second method called
the getDocumentBase() method , which allows the applet to pull the image
from the current folder in which your applet class is stored. Once the graphic is
retrieved, the graphic is assigned to the memory location represented by the
smile variable. The logic of assigning a value to a variable in Java works from
right to left and uses an equal sign.
Next, the drawImage() method in line 24 specifies the location where the
program should draw the graphic. Similar to the drawString() method, the
drawImage() method accepts horizontal and vertical coordinates as parameters
that identify the screen location in pixels. The keyword, this, is required by the
drawImage() method to hold the location of the image while it is being loaded
from disk.
Search WWH ::




Custom Search