Java Reference
In-Depth Information
With the widespread use of graphical user interfaces, users have certain
expectations of how they should interact with GUI components. They expect
to enter text into text boxes and expect to click buttons to trigger an action or
event. Java takes advantage of those expectations and provides the prebuilt
classes for typical GUI components. Programmers have these kinds of tools at
their fingertips, with many ways to implement them.
The init() Method
The constructors for Labels, TextFields, and Buttons are merely storage
locations until the applet actually is displayed on the screen. To display on the
screen, the components must be added to the applet interface using the init()
method. As you learned in Chapter 2, the init() method loads the initial setup of
the applet when execution begins. In the Welcome to My Day applet created in
Chapter 2, the init() method automatically was invoked or initialized by the use
of the paint() method to graphically draw text and an image on the applet
screen.
When the init() method is defined , or coded, as it is in line 30 of the Body
Mass Index Calculator applet code, the programmer takes control over what
attributes and components are added to the applet window when it is initialized
(Figure 3-41).
30
public void init ()
31
{
32
setForeground ( Color .red ) ;
33
add ( companyLabel ) ;
34
add ( heightLabel ) ;
35
add ( heightField ) ;
36
add ( weightLabel ) ;
37
add ( weightField ) ;
38
add ( calcButton ) ;
39
calcButton.addActionListener ( this ) ;
40
add ( outputLabel ) ;
41
logo = getImage ( getDocumentBase () , "logo.gif" ) ;
42
}
43
FIGURE 3-41
Once the applet window is initialized, several methods are used to define the
display of the applet window, including how the components display. As shown
in Figure 3-41, line 32 changes the foreground or text color of the applet window
to red with the setForeground() method . The add() method in lines 33
through 38 and 40 is used to insert the previously declared objects, such as com-
panyLabel and heightField, in the applet window. Both the setForeground() and
add() methods have no object preceding their call, which means the applet itself
is the parent object.
Search WWH ::




Custom Search