Challenge #1: Polyline drawing gizmo


This is an optional challenge lab to help you exercise your Java skills over spring break. It's quite a bit more advanced than the regular labs that we do and covers a lot of concepts in swing and basic data structures that you will need for the next installation of the JFig assignment.

The basic idea is to produce a very, very, very simplistic CAD program that will allow the user to trace a single polyline, reset the drawing space, and change both the background and the foreground colors, as shown below. Note that while the below example is provided as a Java applet, your implementation should use a JFrame instead. Otherwise, try to make your implementation as similar to mine as you can.

I will be glad to answer questions, provide guidance, or review your attempts at this challenge over spring break.

Here are some hints to help you along the way:

  1. You will need to have a class that extends JPanel and overrides the paintComponent(Graphics) method in order to draw on the panel.
  2. JPanels do not produce ActionEvents when they are clicked, so you will need to use a MouseListener in order to respond to clicks by the user on the panel.
  3. After a click is registered by the panel, you will need to redraw the panel. The actual drawing part must take place in the paintComponent(Graphics) method; there is no way to draw the polyline directly on the panel from where you trapped for the click event. This means that you will need to share state information between your event-trapping code and the paintComponent method and force this method to run by calling repaint().
  4. You will have to keep track of every point in the polyline at all times in order to ensure that the polyline is drawn fully and correctly. You could of course do this using an array; however, it a much more efficient and simple approach would be to use a list data structure of some sort, such as Sun's LinkedList implementation.
  5. The "ghosted" line drawn when the mouse moves over the panel will need to be explicitly and completely redrawn, along with the rest of the polyline, every time the panel registers a mouse move. In other words, you will need to do something similar to what you did with the MouseListener, but that will involve a MouseMotionListener instead.
  6. Refer to JColorChooser for help with getting the color-chooser dialog to display.

The finished product: