Java Reference
In-Depth Information
tions do nothing when they're called. So, we override method mouseDragged at lines 23-
28 to capture the coordinates of a mouse drag event and store them as a Point object. Line
26 invokes the MouseEvent 's getPoint method to obtain the Point where the event
occurred and stores it in the ArrayList . Line 27 calls method repaint (inherited indi-
rectly from class Component ) to indicate that the PaintPanel should be refreshed on the
screen as soon as possible with a call to the PaintPanel 's paintComponent method.
Method paintComponent (lines 34-42), which receives a Graphics parameter, is
called automatically any time the PaintPanel needs to be displayed on the screen—such
as when the GUI is first displayed—or refreshed on the screen—such as when method
repaint is called or when the GUI component has been hidden by another window on the
screen and subsequently becomes visible again.
Look-and-Feel Observation 12.13
Calling repaint for a Swing GUI component indicates that the component should be re-
freshed on the screen as soon as possible. The component's background is cleared only if
the component is opaque. JComponent method setOpaque can be passed a boolean argu-
ment indicating whether the component is opaque ( true ) or transparent ( false ).
Line 37 invokes the superclass version of paintComponent to clear the PaintPanel 's
background ( JPanel s are opaque by default). Lines 40-41 draw an oval at the location
specified by each Point in the ArrayList . Graphics method fillOval draws a solid oval.
The method's four parameters represent a rectangular area (called the bounding box ) in
which the oval is displayed. The first two parameters are the upper-left x -coordinate and
the upper-left y -coordinate of the rectangular area. The last two coordinates represent the
rectangular area's width and height. Method fillOval draws the oval so it touches the
middle of each side of the rectangular area. In line 41, the first two arguments are specified
by using class Point 's two public instance variables— x and y . You'll learn more Graphics
features in Chapter 13.
Look-and-Feel Observation 12.14
Drawing on any GUI component is performed with coordinates that are measured from
the upper-left corner (0, 0) of that GUI component, not the upper-left corner of the screen.
Using the Custom JPanel in an Application
Class Painter (Fig. 12.35) contains the main method that executes this application. Line
14 creates a PaintPanel object on which the user can drag the mouse to draw. Line 15
attaches the PaintPanel to the JFrame .
1
// Fig. 12.35: Painter.java
2
// Testing PaintPanel.
3
import java.awt.BorderLayout;
4
import javax.swing.JFrame;
5
import javax.swing.JLabel;
6
7
public class Painter
8
{
Fig. 12.35 | Testing PaintPanel . (Part 1 of 2.)
 
Search WWH ::




Custom Search