Tutorial 11: Sort Animation Revisited


Introduction

This tutorial covers linear equations for plotting numbers onto a JPanel.  It serves to jump start the sort animation homework.


I. Sample Program

Create a local directory comp212/tutorials/11 for this lab and copy the files ~/comp212/tutorials/11/*.java and ~/comp212/tutorials/11/*.class.  These are the Java source code and byte code for a GUI application that animates the various sorting algorithms discussed in the lectures. To see how the application behaves, run the command: java SortControl. Play around with this program to see how it behaves.  The program is designed according to the MVC pattern as shown in the UML diagram below.

MVC.png (28590 bytes)

In the above diagram, the model is an array of IOrdered objects that is to be sorted according to a concrete ACompareSorter selected at runtime.   SortGUI is the view.  It has a GraphCanvas where the data array is plotted and animated.  The design of GraphCanvas is identical to that of BodyPartsCanvas in lab 04: it has an IDrawable object to draw on its graphics context.   The IDrawable object in this case is an inner object of  SortControl, the controller: SortControl.GraphCommand.  It is both an IDrawable and and ILambda.   It makes uses of ArrayMapCar to plot each element in the data array on the GraphCanvas.  It is SortControl.GraphCommand that does all the plotting of the array elements.

II. y = m*x + b

We want to plot an array of integers on a JPanel as rectangular bars with appropriate heights and widths. The graphics method to use here is Graphics.fillRect (int x, int y, int width, int height).  It is important to first understand the orientation of the x-y coordinate system in Java graphics.  As in most graphics systems, the x-coordinate of the graphics context of the JPanel extends form left to right, while the y-coordinate extends from top to bottom.  The origin of the coordinate system is at the upper left corner of the bounding rectangle. 

To have a "nice" plotting of a number A[i] on a JPanel, we use the simple transformation y = m * A[i] + b to map A[i] to the plane of the JPanel.  Let maxVal be the maximum value in the given integer array, and let minVal be the minimum value in the given array.  Plugging maxVal and minVal into the equation y = m * A[i]+ b, we get

We arbitrarily assign a value to maxY and minY, and then solve for m (the slope) and b (the y-intercept).  We now use the equation y = m*A[i] +b for all element A[i] in the given array.  We can think of the index i as an x-coordinate, and y = m * A[i] + b as its y-coordinate.

Exercises:

1. Solve the above system of linear equations by hand.  Compare your solution for m and b with the one in the code for SortControl$GraphCommand.

2. Use your equation y = m * A[i] + b to draw an appropriate rectangular bar for A[i] onto the JPanel (look at the code for SortControl given in homework #3).   Experiment!  Have fun!


dxnguyen@cs.rice.edu

revised 04/09/00