Monday, August 11, 2008

Simple Mouse Interaction in Java

Building on the basic graphics we've done in Very Basic Java Graphics--3 Examples and A Most Basic Graphics App we'll be adding mouse interaction in this example.


This program adds the ability to respond to
mouse events to the BasicPanel program.

The mouse clicks are used to draw on the
panel area using drawline instructions.


// Import the basic necessary classes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MousePanel extends JPanel implements MouseListener{

public MousePanel(){

int pointX, pointY, oldX, oldY;

public void paintComponent(Graphics g){
// Draw a line from the prior mouse click to new one.

public void mouseClicked(MouseEvent mouse){
// Copy the last clicked location into the 'old' variables.
// Get the location of the current mouse click.
pointX = mouse.getX();
pointY = mouse.getY();
// Tell the panel that we need to redraw things.

/* The following methods have to be here to comply
with the MouseListener interface, but we don't
use them, so their code blocks are empty. */
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mousePressed(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }

public static void main(String arg[]){
JFrame frame = new JFrame("MousePanel");

MousePanel panel = new MousePanel();

To add mouse interaction, we're taking advantage of an interface from the package called MouseListener. When we implement MouseListener as part of our JPanel class, then call addMouseListener(this) as part of our MousePanel() constructor, our program is "wired up" to the mouse, so that our MousePanel gets mouse events from the JVM.

Implementing the MouseListener interface requires that we implement all the methods called for by the interface. We only use MouseClicked() in this example, however, so it's the only one that has code in its code block.

This program lets you draw by clicking the mouse at various places in the MousePanel's drawing area, drawing a line from the prior click location (or from top left for the first click) to the location of the current click.

Here's a little challenge for you:

Change the program so that it doesn't draw a line from upper left on the first click, but instead draws a dot in the location of the first click. Later clicks will then draw lines from the prior click's location.

Hint: If you set the initial oldX and oldY values to a value that isn't in the visible MousePanel area, you can tell if there haven't been any prior clicks.