Java Reference
In-Depth Information
Section 12.14 showed how to track mouse events in a
JPanel
. In this section, we use a
JPanel
as a
dedicated drawing area
in which the user can draw by dragging the mouse. In
addition, this section demonstrates an event listener that extends an adapter class.
Method
paintComponent
Lightweight Swing components that extend class
JComponent
(such as
JPanel
) contain
method
paintComponent
, which is called when a lightweight Swing component is dis-
played. By overriding this method, you can specify how to draw shapes using Java's graph-
ics capabilities. When customizing a
JPanel
for use as a dedicated drawing area, the
subclass should override method
paintComponent
and call the superclass version of
paint-
Component
as the first statement in the body of the overridden method to ensure that the
component displays correctly. The reason is that subclasses of
JComponent
support
trans-
parency
. To display a component correctly, the program must determine whether the
component is transparent. The code that determines this is in superclass
JComponent
's
paintComponent
implementation. When a component is transparent,
paintComponent
will not clear its background when the program displays the component. When a compo-
nent is
opaque
,
paintComponent
clears the component's background before the compo-
nent is displayed. The transparency of a Swing lightweight component can be set with
method
setOpaque
(a
false
argument indicates that the component is transparent).
Error-Prevention Tip 12.1
In a
JComponent
subclass's
paintComponent
method, the first statement should always
call the superclass's
paintComponent
method to ensure that an object of the subclass dis-
plays correctly.
Common Programming Error 12.4
If an overridden
paintComponent
method does not call the superclass's version, the sub-
class component may not display properly. If an overridden
paintComponent
method calls
the superclass's version after other drawing is performed, the drawing will be erased.
Defining the Custom Drawing Area
The
Painter
application of Figs. 12.34-12.35 demonstrates a customized subclass of
JPan-
el
that's used to create a dedicated drawing area. The application uses the
mouseDragged
event handler to create a simple drawing application. The user can draw pictures by dragging
the mouse on the
JPanel
. This example does not use method
mouseMoved
, so our
event-lis-
tener class
(the
anonymous inner class
at lines 20-29 of Fig. 12.34) extends
Mouse-
MotionAdapter
. Since this class already declares both
mouseMoved
and
mouseDragged
, we
can simply override
mouseDragged
to provide the event handling this application requires.
1
// Fig. 12.34: PaintPanel.java
2
// Adapter class used to implement event handlers.
3
import
java.awt.Point;
4
import
java.awt.Graphics;
5
import
java.awt.event.MouseEvent;
Fig. 12.34
|
Adapter class used to implement event handlers. (Part 1 of 2.)