Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Standard Applet Methods 237

The main time the paint()method is called is when something changes in
the browser or the operating system running the browser. For example, if a
user closes a window of another program that was in front of the browser,
the paint()method is called to redisplay everything in the applet.


The paint()method takes a single argument, a Graphicsobject from the
java.awtpackage:


public voidpaint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
// display statements go here
}


The Graphicsclassrepresents a graphical context, an environment in which
something can be displayed. As you did with Swing applications, you
should cast this to a Graphics2Dobject from the java.awtpackage to use
Swing’s graphical capabilities.


Later this hour, you learn about drawString(), a method for displaying
text in the Graphics2Dclasses.


If you are using a Graphicsor Graphics2Dobject in your applet, you
should add the following importstatementsbefore the classstatement at
the beginning of the source file:


importjava.awt.Graphics;
importjava.awt.Graphics2D;


Alternatively, you can make all java.awtclasses available by using the
wildcard character “*”:


importjava.awt.*;


Initializing an Applet


The init()method is called once—and only once—when an applet is run.
It’s an ideal place to set up values for objects and variables that are needed
for the applet to run successfully. This method also is a good place to set
up fonts, colors, and the applet window’s background color. Here’s an
example:


public voidinit() {
FlowLayout flo = new FlowLayout();
setLayout(flo);
JButton run = new JButton(“Run”);
add(run);
}

Free download pdf