Lab 7
More with Interfaces and AWT

October 26, 2009


Exercise 4 Review

Download the following files:

Part 1

If you try to run the above code, you should get something that looks like this:

The end result of part one of this exercise is to get shapes to be drawn around a point clicked in the white portion of the frame. The code in creates the frame and the buttons. The focus of this exercise will bein in and

    public class DrawCanvas extends Canvas implements ActionListener, MouseListener{
	//The following constants should be used
	public static final int CIRCLE = 0;
	public static final int SQUARE = 1;
	public static final int TRIANGLE = 2;
	private int selectedObject = CIRCLE;
	private MyShape drawnShape;

Notice that there is one variable here to store the drawn object. Looking at

    /* Interface example for lab 10/26
     * @author Scotty Smith
    public interface MyShape {
	public void drawShape(Graphics g);

So, there is an interface declared that defines's interaction with the shapes. BUT the shapes have not been created yet. So, part one of this exercise is to create those shapes. Add code to for:

Write the code in drawShape so that the shape is drawn around some point where the mouse is clicked.

Next, need to add code to

     * Put code in here to change the drawn object
    public void mouseClicked(MouseEvent m) {

         //This code forces the paint method of this object to be called

Note: You can get the x and y coordinate of the mouse click from the MouseEvent object

Finally, finish the paint method. It should draw the object stored in drawnShape.

    public void paint(Graphics g){
         //Put code in here to draw "drawnShape"

Once you have finished the above, you should be able to click a button, then click in the white area to draw a shape.

Part 2

Change the code to generate a random color for every drawn shape:

Part 3

Change the code to add a new shape that is drawn at each step.

You will want to add a new button (in and code in to clear the canvas when pressed.

Part 4

Add a new shape (e.g. a Star). Use DrawPolygon to accomplish this task.