Java Reference
In-Depth Information
17
18
application.add(panel); // add the panel to the frame
application.setSize( 250 , 250 ); // set the size of the frame
application.setVisible( true ); // make the frame visible
19
20
21
}
22
} // end class DrawPanelTest
Fig. 4.19 | Creating JFrame to display DrawPanel . (Part 2 of 2.)
Line 6 uses the keyword extends to indicate that class DrawPanel is an enhanced type
of JPanel . The keyword extends represents a so-called inheritance relationship in which
our new class DrawPanel begins with the existing members (data and methods) from class
JPanel . The class from which DrawPanel inherits , JPanel , appears to the right of keyword
extends . In this inheritance relationship, JPanel is called the superclass and DrawPanel is
called the subclass . This results in a DrawPanel class that has the attributes (data) and
behaviors (methods) of class JPanel as well as the new features we're adding in our Draw-
Panel class declaration—specifically, the ability to draw two lines along the diagonals of
the panel. Inheritance is explained in detail in Chapter 9. For now, you should mimic our
DrawPanel class when creating your own graphics programs.
Method paintComponent
Every JPanel , including our DrawPanel , has a paintComponent method (lines 9-22),
which the system automatically calls every time it needs to display the DrawPanel . Method
paintComponent must be declared as shown in line 9—otherwise, the system will not call
it. This method is called when a JPanel is first displayed on the screen, when it's covered
then uncovered by a window on the screen, and when the window in which it appears is
resized . Method paintComponent requires one argument, a Graphics object, that's provid-
ed by the system when it calls paintComponent . This Graphics object is used to draw lines,
rectangles, ovals and other graphics.
The first statement in every paintComponent method you create should always be
super .paintComponent(g);
which ensures that the panel is properly rendered before we begin drawing on it. Next,
lines 14-15 call methods that class DrawPanel inherits from JPanel . Because DrawPanel
extends JPanel , DrawPanel can use any public methods of JPanel . Methods getWidth
and getHeight return the JPanel 's width and height, respectively. Lines 14-15 store these
values in the local variables width and height . Finally, lines 18 and 21 use the Graphics
variable g to call method drawLine to draw the two lines. Method drawLine draws a line
 
Search WWH ::




Custom Search