Java Reference
In-Depth Information
In order to handle an event of type X , one needs to create an event listener and regis-
ter it with the event source. The event listener belongs to the X Listener class, where X
should be substituted with the type of the event (e.g., MouseListener , KeyListener ,
etc.). The event, which will be of type X Event (e.g., MouseEvent , KeyEvent , etc.), will
be passed as a parameter to the method of the event listener. Call the add X Listener
method on the event source to register the event listener with it.
With every rule, there are exceptions. Here the exception is that there is a MouseEvent ,
but there is no MouseMotionEvent .
Goingbacktoourdrawingprogram,wewillfirstcreatea MyShape class. A freehand
object will be represented by an object of type MyShape .
class MyShape {
private ArrayList < Point2D > points = new ArrayList <> () ;
public MyShape( Point2D point ) {
points .add(point) ;
public MyShape ( ) {}
public void addPoint(Point2D point ) {
points .add(point) ;
public void drawShape(Graphics2D g) {
g. setPaint(Color .RED) ;
if ( p o i n t s . s i z e ( )==0)
return ;
} Point2D start=points .get(0) ;
for (Point2D end : points ) {
g.draw( new Line2D.Double(start ,end)) ;
A shape is stored as an ArrayList of points. The drawShape method takes as input a
drawing brush. It sets the paint color to red and then draws the shape by connecting the
dots of the shape with lines. Note that we have added an empty constructor. Although we
will not use it in our code, good programming practices suggest that an empty constructor
be added to a class that contains constructors. The reason is that adding a constructor
to a class removes the default empty constructor and can invalidate code that previously
In our program, we will create a window and a panel inside it. We will do the drawing
inside the panel and we will register our mouse listeners with the panel. In general, a mouse
listener can be registered with both the window and the panel. However, registering it with
the panel is usually more convenient because the drawing happens inside the panel and the
mouse listener usually updates the data for the drawing. When the user presses the left key
of the mouse, we will start drawing a new shape. Here is the code that handles this event.
class MyPanel extends JPanel {
ArrayList < MyShape > shapes = new ArrayList <> () ;
Search WWH ::

Custom Search