Aqua Phoenix
     >>  Research >>  OOP  


18. Using Graphics to make Applets

18.1 Summary

  • Paneled Applet where each panel is some extension of a Canvas or Panel
  • Mouse Listeners

18.2 Contents

18.2.1 Paneled Applet where each panel is some extension of a Canvas or Panel

Presentation and discussion of an applet with multiple panels, each of which now contains customized Graphics. For some of these graphical panels, we will implement a new type of Listener, namely the MouseListener.

18.2.2 Mouse Listeners

The Event Listeners from before merely captured singular events, like a click, or a selection. For more complicated graphical components, we would want to use Event Handlers that can tell us exactly where the mouse is, i.e. the coordinates of the Mouse, when the Mouse has moved, whether or not a mouse button is being pressed, etc. This type of information is necessary in order to develop a paint program, for example. Recall one of the first tools you used to learn about data types. The tool itself is programmed in Java. Each datanode has some x,y position, and whenever you select a datanode and move it, the x,y position changes. That particular tool uses a lot of MouseListeners, as it is entirely graphical with lots of user interaction.

In order to use MouseListeners, we will look at the bare minimum framework:

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

public class myObject extends Panel implements MouseListener, MouseMotionListener {

  public void myObject() {


  // from MouseListener
  public void mouseClicked(MouseEvent e) { }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }

  // from MouseMotionListener
  public void mouseDragged(MouseEvent e) { }
  public void mouseMoved(MouseEvent e) { }

Notice that we are implementing 2 interfaces, both of which capture some properties of mouse events. Let's say that we wish to capture mouse clicks, and we would like to know at what mouse cursor position the click has occured. Here is how we would achieve our goal:

  public void mouseClicked(MouseEvent e) {

    int x = e.getX();
    int y = e.getY();

Again, MouseEvent is an object that is passed to the mouseClicked method. Because we are only dealing with one mouse, we need not figure out the source of the click. In order to retrieve the x and y positions, we call methods getX() and getY() from the MouseEvent object. These two methods are the most useful from any MouseEvent.

Take a look at all the mouse actions in action: