Tutorial 2

From Java Tutorials

Jump to: navigation, search

This tutorial will cover implementing an interface to handle mouse input to add interactivity to your drawing code. Note that if you've been looking at the Slime Volleyball code before, the mechanism for handling events is different to that listed here - this is the new way of doing things. The Slime code uses the old way for backwards compatibility purposes, the new way is much nicer.


[edit] Mouse events

Firstly, we will write code to handle mouse input. To do this, we need to figure out which interface to implement. In the java.awt.event package, there are a number of sub-classes of Event that funnily enough, are for event handling, such as mouse clicks, key presses etc. If you have a look, you'll notice classes named something like MouseEvent, and interfaces like MouseListener. MouseListener looks like it's an appropriate interface to implement. So, create a new project and start with basic code like this:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Tutorial_2a extends Applet implements MouseListener {

  public void init() {


The bold statements show the changes from the last tutorial. In this case, we want to implement the MouseListener interface, so obviously that needs to be specified, and it is in the java.awt.event package, so tell Java to import that package. Even though it is specified that this applet now implements the MouseListener interface, we need to explicitly tell Java to call the relevent methods if mouse input occurs; this is what the addMouseListener(this) does. If you don't do this, then your code compile and run ok, and you can click your mouse away as much as you like and the applet won't do anything! So it's important, and something that people seem to commonly forget to add.

Now, the API says that there are five methods to be implemented in the MouseListener interface:

 void mouseClicked(MouseEvent e)
          Invoked when the mouse button has been clicked (pressed and released) on a component.
 void mouseEntered(MouseEvent e)
          Invoked when the mouse enters a component.
 void mouseExited(MouseEvent e)
          Invoked when the mouse exits a component.
 void mousePressed(MouseEvent e)
          Invoked when a mouse button has been pressed on a component.
 void mouseReleased(MouseEvent e) 
          Invoked when a mouse button has been released on a component.

We will just concentrate on the mousePressed() method (which as stated above, deals with when the mouse button is pressed), and have empty method bodies for the remaining four (though of course you can experiment with them later on!) So, put this in your Tutorial_2.java file (or whatever you called it):

public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }

Now, what does the MouseEvent class do? It's created to store the data of a mouse click, such as:

  • the location of the mouse click (using e.getX() and e.getY() )
  • which button is pressed (which we can access via e.getButton(), which will return one of MouseEvent.NOBUTTON, MouseEvent.BUTTON1, MouseEvent.BUTTON2 or MouseEvent.BUTTON3)

[edit] Exercise 1

So now, your mission, should you choose to accept it, is to write a mousePressed() method that, when the user clicks, will draw a red circle of radius 30 pixels at that point. Use getGraphics() to get a reference to the graphics object that draws on the applet. You should end up with something like this (click inside the box, there's an applet in there!):

If you're stuck, then you can see a solution by clicking __HIDER__
	public void mousePressed(MouseEvent e) {
		Graphics g = getGraphics();
		int radius = 30;
		g.fillOval(e.getX()-radius, e.getY()-radius, 2*radius, 2*radius);

Note that even though we know the radius will be 30 pixels, it's stored in a variable rather than being hard coded into the code as a magic number (i.e., g.fillOval(e.getX()-30, e.getY()-30, 60, 60);. Don't use magic numbers. They are bad and will come back to haunt you if you want to make changes to your code later on...

You might notice that your circles might disappear if you open another window on top of the Appletviewer window, and then go back to your applet. That's ok. The reason for this is that when your Appletviewer window becomes the top window again, your paint() method is called to redraw everything inside the window. Except in this case, paint() does.... nothing (because the drawing is all done inside a different method, mousePressed(). We'll come back to this problem later.

[edit] Exercise 2

In this exercies, we will use the drawLine() method of the Graphics class to draw a series of connected lines. The user will click the starting point, and then for each subsequent mouse click, we will draw a line from the last point to the clicked point. Hint: you will need some instance variables to remember the location of the last click. Your applet should look something like this (click in the box):

Sample code is available here if you are stuck: __HIDER__
	// some instance variables to store the x and y coordinates of the last click	
	int lastX, lastY;
	// has the user clicked on the applet yet? initially, no.
	boolean hasBeenClicked = false;
	// called when someone clicks on the applet.
	public void mousePressed(MouseEvent e) {
		// only execute this block of code if the mouse has been clicked before
		if (hasBeenClicked)
			Graphics g = getGraphics();
			// draw a line from (lastX, lastY) to the newly clicked point.
			// It's essential that you use e.getX() rather than just getX()
			// which will get the x coordinate of the applet, not the click!
			g.drawLine(lastX, lastY, e.getX(), e.getY());
		// either way, store the new x and y values 
		lastX = e.getX();
		lastY = e.getY();
		// and yes, the applet has now been clicked.
		hasBeenClicked = true;

If you are interested then you can read Sun's lesson on How to Write a Mouse Listener

Java Games Programming Tutorials

Getting started
Tutorial 1 - Hello World | Tutorial 2 - Handling mouse input
Tutorial 3 - Handling Key Input | Tutorial 4 - Threads and Animations
to be continued...
oneslime.net programming forum

Personal tools