Last week, we took a look at the mechanics of extending a Frame object

(that is, a window that can be rendered in a graphical desktop

environment) with a modified Canvas object. Previously, we just

modified the Canvas by attaching an image to it, such that the image

was displayed in the Frame when it was made visible.

This week, we'll use one of Arthur Griffith's applications (Arthur is a

writer and programmer -- http://www.belugalake.com) to attach a

differently specialized class to the Canvas, and in turn to the Frame.

We'll hook up a custom class called FollowMousePanel, but it will

implement a class called MouseMotionListener. As listener events do,

MouseMotionListener generates event objects when specified things

happen. This class concerns detecting clicks and drags of the mouse. It

has two methods, mouseMoved() and mouseDragged(), both of which

FollowMousePanel overrides.

When the mouse moves (relocated without its button pressed), a

mouseMoved event occurs and mouseMoved() can act on it. Ditto for a

drag (which is the same as a move, but with a button depressed). In

that case, a mouseDragged event occurs and mouseDragged() can act on it.

Here's the code for you:

import java.awt.*;

import java.awt.event.*;

public class FollowMouseMotion extends Frame {

public static void main(String[] arg) {

new FollowMouseMotion();


FollowMouseMotion() {


addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{ System.exit(0); } } );

FollowMousePanel mp = new FollowMousePanel();





class FollowMousePanel extends Canvas

implements MouseMotionListener {

String description = "";

FollowMousePanel() {




public void paint(Graphics g) {



public void mouseMoved(MouseEvent event) {

description = "Moved (" + event.getX() +

"," + event.getY() + ")";



public void mouseDragged(MouseEvent event) {

description = "Dragged (" + event.getX() +

"," + event.getY() + ")";





ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon