Java Reference
In-Depth Information
rectangles (see
Figure 22
). You'll soon see how to produce more interesting drawings.
The purpose of this example is to show you the basic outline of a program that creates
a drawing. You cannot draw directly onto a frame. Whenever yo
u want to show
anything inside a frame, be it a button or a drawing, you have to
construct a component
object and add it to the frame. In the Swing toolkit, the
JComponent
class represents
a blank component.
59
60
Figure 22
Drawing Rectangles
Since we don't want to add a blank component, we have to modify the
JComponent
class and specify how the component should be painted. The solution is to define a
new class that extends the
JComponent
class. You will learn about the process of
extending classes in
Chapter 10
. For now, simply use the following code as a template.
In order to display a drawing in a frame, define a class that extends the
JComponent
class.
public class RectangleComponent extends JComponent
{
public void paintComponent(Graphics g)