An Applet with a Canvas


The applet's real estate is the area within the border

Source

AnAppletWithCanvas.java
import java.applet.*;
import java.awt.*;

public class AnAppletWithCanvas extends Applet {
	public void init() {
		Button larger = new Button("Larger");
		add(larger);

		Button smaller = new Button("Smaller");
		add(smaller);

		add(new CircleCanvas(larger, smaller));
	}
}
CircleCanvas.java
import java.awt.*;
import java.awt.event.*;


public class CircleCanvas extends Canvas implements ActionListener {
	CircleCanvas(Button larger, Button smaller) {

		this.larger = larger;
		larger.addActionListener(this);

		this.smaller = smaller;
		smaller.addActionListener(this);

		setSize(100, 100);

		setBackground(Color.yellow);
	}

	public void paint(Graphics g) {
		g.setColor(Color.blue);
		g.drawOval(upperLeftX, upperLeftY, diameter, diameter);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == larger)
			diameter++;
		else 
			diameter--;
		repaint();
	}

	Button larger, smaller;

	int 
		upperLeftX = 10, 
		upperLeftY = 20, 
		diameter = 10;
}

Description and Objective

An applet that uses a canvas as a dedicated area for drawing graphics. better layout control.

Notes

Interface Components and Graphics on the Applet's Surface The Canvas Class Subclassing the Canvas Class

This Applet's Behavior

The AnAppletWithCanvas Class The LineCanvas Class

Things to Do

API work Playing With the Applet Place the following applets on the same page:
  1. Modify the AnAppletWithCanvas, adding buttons to move the circle up and down
  2. Add a second canvas that does the same thing as the first canvas, but displays a rectangle rather than a circle (as your starting point you can use either the original applet or the one in #1-- with the up/down buttons)
  3. (Optional) It was mentioned that the canvas subclass usually listens to the buttons that control its graphic behavior. Change the structure of the applet and canvas subclasses so that the applet listens to the buttons and informs the canvas (via method calls) of the changes to be made.
  4. (Optional-- don't bother unless you've done the first optional) Add a second canvas and have both canvases react to the larger/smaller buttons