Java Reference
In-Depth Information
{
Drawing instructions go here
}
}
The extends keyword indicates that our component class,
RectangleComponent , inherits the methods of JComponent . However, the
RectangleComponent is different from the plain JComponent in one respect:
The paintComponent method will contain instructions to draw the rectangles.
Place drawing instructions inside the paintComponent method. That method is
called whenever the component needs to be repainted.
When the window is shown for the first time, the paintComponent method is
called automatically. The method is also called when the window is resized, or when it
is shown again after it was hidden.
The paintComponent method receives an object of type Graphics . The
Graphics object stores the graphics stateȌthe current color, font, and so on, that are
used for drawing operations.
The Graphics class lets you manipulate the graphics state (such as the current
color).
However, the Graphics class is primitive. When programmers clamored for a more
object-oriented approach for drawing gra phics, the designers of Java created the
Graphics2D class, which extends the Graphics class. Whenever the Swing toolkit
calls the paintComponent method, it actually passes a parameter of type
Graphics2D . Programs with simple graphics do not need this feature. Because we
want to use the more sophisticated methods to draw two-dimensional graphics objects,
we need to recover the Graphics2D . This is accomplished by using a cast:
60
61
The Graphics2D class has methods to draw shape objects.
Use a cast to recover the Graphics2D object from the Graphics parameter of
the paintComponent method.
Search WWH ::




Custom Search