Java Reference
In-Depth Information
B.3.2 graphics
As mentioned in Section B.2.5, graphics are drawn by using a JPanel object.
Specifically, to generate graphics, the programmer must define a new class
that extends JPanel . This new class provides a constructor (if a default is unac-
ceptable), overrides a method named paintComponent , and provides a public
method that can be called from the canvas's container. The paintComponent
method is
Graphics are drawn
by defining a class
that extends
JPanel . The new
class overrides the
paintComponent
method and pro-
vides a public
method that can be
called from the
canvas's container.
void paintComponent( Graphics g );
Graphics is an abstract class that defines several methods. Some of these are
void drawOval( int x, int y, int width, int height );
void drawRect( int x, int y, int width, int height );
void fillOval( int x, int y, int width, int height );
void fillRect( int x, int y, int width, int height );
void drawLine( int x1, int y1, int x2, int y2 );
void drawString( String str, int x, int y );
void setColor( Color c );
Graphics is an
abstract class that
defines several
drawing methods.
In Java, coordinates are measured relative to the upper left-hand corner of
the component. drawOval , drawRect , fillOval , and fillRect all draw an object
of specified width and height with the upper left-hand corner at coordinates
given by x and y . drawLine and drawString draw lines and text, respectively.
setColor is used to change the current color; the new color is used by all draw-
ing routines until it is changed.
In Java, coordinates
are measured rela-
tive to the upper
left-hand corner of
the component.
It is important that the first line of paintComponent calls the superclass's
paintComponent .
Figure B.8 illustrates how the canvas in Figure B.1 is implemented. The
new class GUICanvas extends JPanel . It provides various private data members
that describe the current state of the canvas. The default GUICanvas constructor
is reasonable, so we accept it.
The data members are set by the public method setParams , which is provided
so that the container (that is, the GUI class that stores the GUICanvas ) can commu-
nicate the state of its various input components to the GUICanvas . setParams is
shown at lines 3 to 13. The last line of setParams calls the method repaint .
It is important that
the first line of
paintComponent calls
the superclass's
paintComponent .
The repaint method schedules a component clearing and subsequent call
to paintComponent . Thus all we need to do is to write a paintComponent method
that draws the canvas as specified in the class data members. As can be seen
by its implementation in lines 15 to 35, after chaining up to the superclass,
paintComponent simply calls the Graphics methods described previously in this
appendix.
The repaint
method schedules
a component clear-
ing and then calls
paintComponent .
 
Search WWH ::




Custom Search