The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Learning the Java Language
Lesson: Objects and Classes in Java

Reality Break! The Spot Applet

Let's do something a bit more fun and look at an applet, Spot. With this applet, we show you how to subclass another class and implement an interface. The last section of this lesson, Using an Inner Class to Implement an Adapter, shows you two alternative implementations of this class, both of which use inner classes.

Here's the Spot applet running. The applet displays a small spot when you click over the applet with the mouse:


Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go to example-1dot1/Spot.html. For more information about running applets, refer to About Our Examples.
And here's the source code for the applet:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Spot extends Applet implements MouseListener {
    private java.awt.Point clickPoint = null;
    private static final int RADIUS = 7;

    public void init() {
	addMouseListener(this);
    }
    public void paint(Graphics g) {
	g.drawRect(0, 0, getSize().width - 1,
			 getSize().height - 1);
	if (clickPoint != null)
	    g.fillOval(clickPoint.x - RADIUS,
		       clickPoint.y - RADIUS,
		       RADIUS * 2, RADIUS * 2);
    }
    public void mousePressed(MouseEvent event) {	
	clickPoint = event.getPoint();
	repaint();
    }
    public void mouseClicked(MouseEvent event) {}
    public void mouseReleased(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
}
The extends clause indicates that the Spot class is a subclass of Applet. The next section, Extending a Class, talks about this aspect of Spot. The implements clause shows that Spot implements one interface named MouseListener. Read about this aspect of the Spot class in Implementing an Interface later in this lesson.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search