Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Steps to Java Internationalization (i18n)

Java Applets in Education

Java #6 I Wanna hold your hand - longer

Java #5 I Wanna hold your hand

Java Applets #4

Java Applets #3

Java Applets #2

Java Applets #1

Mouse Event Handling in Java 1.0

You are here: irt.org | Articles | Java | Mouse Event Handling in Java 1.0 [ previous next ]

Published on: Friday 21st August 1998 By: Stephen Saunders

Introduction

The purpose of this article is to demonstrate a technique for interacting with the mouse by using the event handling methods in the Java 1.0 event model.

Java handles interactivity - things like mouse clicks, and key presses - with special objects called events. If you want your applet to be able to react to a user's input, event handling is a technique you'll have to learn.

In keeping with that goal, we're going to write a real-world example that uses event handling. By the end of this article, you should have a Scribble applet: an applet that allows you to draw freehand (much like a graphics paint program).

If you'd like to follow along with this article, you can begin with the following code. This code will produce a large, blank applet that does absolutely nothing.

import java.applet.Applet;

public class Scribble extends Applet
{
}

Also, create an HTML file to view the applet with the following tag in it:

<APPLET CODE="Scribble.class" WIDTH="400" HEIGHT="400"> </APPLET>

There is only one thing that we want to add to this applet:

  1. the ability to drag the mouse on the surface of the applet and leave a line behind

Events in General

Events are special objects that get created by the Java runtime system every time something occurs. All the details about the occurance get collected, an Event object gets created, all the details get put into that Event, and then that event is handed to the applet. The applet then goes through the process of trying to figure out what kind of event it was, and what to do with it.

Scribbling - The Mouse Events

Applets have a series of six methods that you can use to control how the mouse behaves. One senses when the mouse button is pushed down; one senses when it is released; one senses when the mouse is moving; one senses when the mouse is being dragged; one senses when the mouse first comes into the applet's area of the screen; and one senses when the mouse leaves the applet and heads back to the rest of the HTML page. You can use any or all of these six methods to provide functionality to your applet.

The six methods are mouseUp(), mouseDown(), mouseMove(), mouseDrag(), mouseEnter(), and mouseExit(). Their method declarations are very similar, and are shown below:

public boolean mouseUp(Event e, int x, int y)
public boolean mouseDown(Event e, int x, int y)
public boolean mouseMove(Event e, int x, int y)
public boolean mouseDrag(Event e, int x, int y)
public boolean mouseEnter(Event e, int x, int y)
public boolean mouseExit(Event e, int x, int y)

These six methods are the only easy way to keep track of what the user is doing with her mouse. In order to make our scribble applet work, we've got to try and think of a way to break down the use of the applet into these six common actions. Thinking in terms of these six different mouse methods, scribbling can be summarized as actually three distinct actions.

How does this translate into our mouse methods?

what happens when the user pushes the mouse button? (mouseDown) the scribbling starts at the point the mouse was pushed
what happens when the user lets go of the mouse button? (mouseUp) the scribbling stops
what happens when the mouse is just moving over the applet? (mouseMove) nothing
what happens when the mouse is dragged over the applet? (mouseDrag) there is a line drawn behind the mouse
what happens when the mouse enters the applet's space? (mouseEnter) nothing
what happens when the mouse leaves the applet's space? (mouseExit) nothing

What's actually going to happen when the user uses our applet? She's going to move the mouse all around (lots of mouseMove() methods being called). Then she'll choose a spot to begin drawing, and press down (there's a mouseDown() method). We'll want to remember that point she pressed on, because that's where the scribbling should begin. Then, she'll drag the mouse somewhere. Every time the mouse gets dragged, even one pixel away, the mouseDrag() method gets called. So we want our applet to simply draw a line from the new mouse position to the old mouse position. Then, we'll remember the new pixel the mouse is pointing at. That way, as the user drags across the surface of the applet, out applet will quickly draw hundreds and hundreds of very short, connected lines. Finally, she'll let go of the button. When she lets go, nothing happens. The scribbling just stops.

With the above reasoning in mind, you can create psuedocode, an odd-looking mix of Java and English (or whatever your native tounge happens to be) that gives us a basis from which to proceed.

import java.applet.Applet;

public class Scribble extends Applet
{
  // we need a variable to remember the last mouse position
  
  /*
  
  mouseDown()
  {
    remember the point the mouse is currently at
  }
  
  mouseDrag()
  {
    draw a line between this point and the last point the mouse was at
    the current point now becomes the last point
  }
  
  */
}

Our next step is to change the English parts above into Java. First of all, a point is made up of two numbers: an X coordinate (how far from the right/left), and a Y coordinate (how far from the top/bottom). So we'll require two variables, which I will call xpoint and ypoint. These numbers will always be whole numbers, never fractions or decimals, so the int (integer) data type will suit us fine.

int xpoint;
int ypoint;

Next, we change the mouse methods to use their actual method declarations. Both methods are public, have a boolean return type, and take three arguments: an Event object, an x coordinate, and a y coordinate. I'll call these e, x, and y respectively.

public boolean mouseDown(Event e, int x, int y)

public boolean mouseDrag(Event e, int x, int y)

The x and y coordinates that are being passed into these methods represent the actual point the user clicked (or dragged, or moved...) on. If the user pushed the mouse button at the position (50,75), then our applet's mouseDown() method would be called with x equal to 50 and y equal to 75. This is the exact information we said we wanted to store. The body of our mouseDown() method should grab those two numbers, and save them in our two variables.

public boolean mouseDown(Event e, int x, int y)
{
  xpoint = x;
  ypoint = y;
}

We're almost done. Here's our progress so far.

import java.applet.Applet;

public class Scribble extends Applet
{
  int xpoint;
  int ypoint;
  
  public boolean mouseDown(Event e, int x, int y)
  {
    xpoint = x;
    ypoint = y;
  }
  
  public boolean mouseDrag(Event e, int x, int y)
  {
    /*
    draw a line between this point and the last point the mouse was at
    the current point now becomes the last point
    */
  }
  
}

Drawing Lines

The question now becomes: How do you draw lines on the screen? Here's a brief explanation.

The screen is represented by a special Java object called a Graphics object. You have to have a Graphics object before you can draw on anything. Graphics objects have many methods built-in, for drawing all sorts of shapes and patterns. In this exercise, there is only one method we are interested in: drawLine(). drawLine() requires 4 pieces of information to function properly: it needs to know the x coordinate and the y coordinate where the line should begin, and the x coordinate and the y coordinate where the line should stop. So to draw a line from (10,10) to (50,55), you would use the line:

g.drawLine(10, 10, 50, 55);

NOTE: this will only work, of course, if g is a Graphics object.

So, in our mouseDrag() method, we need to do the following:

In addition to all this, applets have a special method that is used to go find the Graphics object that represents the screen. That method is getGraphics().

Bring it all together, and your code should look like this:

public boolean mouseDrag(Event e, int x, int y)
{
  Graphics g = getGraphics();
  g.drawLine(xpoint, ypoint, x, y);
}

Also, don't forget that mouseDrag() should also update what the last point visited was. We have to put the new point - (x,y) - into our variables - xpoint and ypoint. How? The exact same way we did in mouseDown().

public boolean mouseDrag(Event e, int x, int y)
{
  Graphics g = getGraphics();
  g.drawLine(xpoint, ypoint, x, y);
  
  xpoint = x;
  ypoint = y;
}

Finishing Touches

I'm going to draw your attention to the word "boolean" that appears in both of our mouse method declarations, in case you haven't seen it before. That is the return type of the method: it is the type of information that the method is supposed to spit out (or return) as output. As it stands right now, neither of our mouse methods are returning any output. This is unacceptable to the Java compiler.

A "boolean" is a true or false value, so our mouse methods have to output either "true" or "false". You can send information back out of a method by using the return keyword. Returning information should always be the last thing you do in a method, and, every time you use the mouse methods (except in some advanced circumstances), you will always want to return true.

We'll have to add this line to the end of both our mouse methods:

return true;

There's one other finishing touch to add to our applet, to make it compile properly. We've actually made reference to three different types of Java objects in our code: to an Applet object (up near the top), an Event object (in both mouse methods), and a Graphics object (in mouseDrag()). The Java compiler will have no idea what these object are unless you tell it where to find them. This is the purpose of the import statement.

We've already included the import statement for the Applet class, so we'll only have to add the statements for Event and Graphics. Events and Graphics are both found in the java.awt package.

import java.awt.Event;
import java.awt.Graphics;

The End

Here is your finished code. When you compile this, if you are using the Java Developer's Kit, version 1.1 or later, you will see a compiler deprecation warning. This is not an error: the compiler is telling you that you are programming in the older version of the language (version 1.0). In a future article, we'll reimplement this simple applet using the new event handling model.

import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;

public class Scribble extends Applet
{
  int xpoint;
  int ypoint;
  
  public boolean mouseDown(Event e, int x, int y)
  {
    xpoint = x;
    ypoint = y;
    return true;
  }
  
  public boolean mouseDrag(Event e, int x, int y)
  {
    Graphics g = getGraphics();
    g.drawLine(xpoint, ypoint, x, y);
    xpoint = x;
    ypoint = y;
  }
}

Related items

Steps to Java Internationalization (i18n)

Java Applets in Education

Java #6 I Wanna hold your hand - longer

Java #5 I Wanna hold your hand

Java Applets #4

Java Applets #3

Java Applets #2

Java Applets #1

Feedback on 'Mouse Event Handling in Java 1.0'

©2018 Martin Webb