Due Sunday 30 December at midnight (ish)

The goal of this assignment is to use a bit of the Java 2D graphics and Swing user interface framework to create a simple sketch pad. In the process, you will learn quite a bit about how graphical event-based applications work across a variety of environments, such as the Android mobile device platform.

You should create a Swing application whose main window (frame) contains a canvas on which the user can draw with the mouse. When the user clicks and drags the mouse in the canvas, it starts drawing on the screen. The user can release the mouse button and then begin a new free-hand line drawing elsewhere on the canvas. When the user double-clicks, it should clear the canvas and start a new drawing.

Below is a drawing I made using my SketchPad program. The bottom half (coffee cup, signature, etc.) was done using my tablet pen instead of a typical mouse – it’s a little cleaner than what you can probably obtain using a mouse, unless you have a very steady hand!

The videos on Swing and Java 2D will help you get started, but the basic gist is that you maintain a list of points over which the user has dragged the mouse:

    ArrayList<Point> points = new ArrayList<Point>();

To do that, you need to have a MouseListener as well as a MouseMotionListener. You’ll provide implementations for mouseClicked, mouseDragged, and mouseReleased. They will manipulate the points array appropriately, and then call repaint(). So then within the paint method, you use the points array to determine what lines to draw.

It’s a little tricky to get this exactly right, but even the mistakes can be interesting. Here’s the result of one mistake I made, where instead of drawing a line along the path that you drag, it would draw lines from the origin point (where you first clicked) to all the points of that path.

I have a template that should help you get started: SketchPad.java. As written, this program will draw a line from the origin (0,0) [upper left] to wherever you click. It will also update the status label at the bottom of the window with the x,y coordinate of the point where you clicked.

Enjoy!