What

By David Wall, ITworld |  News

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() {
super("FollowMouseMotion");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); } } );
FollowMousePanel mp = new FollowMousePanel();
add(mp);
pack();
show();
}

class FollowMousePanel extends Canvas
implements MouseMotionListener {
String description = "";
FollowMousePanel() {
addMouseMotionListener(this);
setSize(400,400);
}
public void paint(Graphics g) {
g.drawString(description,20,30);
}
public void mouseMoved(MouseEvent event) {
description = "Moved (" + event.getX() +
"," + event.getY() + ")";
repaint();
}
public void mouseDragged(MouseEvent event) {
description = "Dragged (" + event.getX() +
"," + event.getY() + ")";
repaint();
}
}
}

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question
randomness