Page 618 - Introduction to Programming with Java: A Problem Solving Approach
P. 618

                584 Chapter 14 Exception Handling
 public void writeToFile() throws IOException
{
}
// end writeToFile
PrintWriter fileOut = new PrintWriter("testFile.txt");
try
{
}
fileOut.printf("%s", "This is a test.");
finally
{
}
fileOut.close();
Figure 14.17 Method that uses a finally block to close an output file 14.13 GUI Track and Problem Solving:
Line Plot Example Revisited (Optional) Problem Description
 Earlier in the chapter, we implemented a LinePlot program that plotted a line defined by a sequence of user- specified points. The line plot’s display was less than ideal. It “displayed” the line as a text description of
Apago PDF Enhancer
line segments. For example, this is what the program produces for a five-segment line that goes from point (0,0) to (1,3) to (2,1) to (3,2) to (4,2) to (5,1):
(0,0)–(1,3), (1,3)–(2,1), (2,1)–(3,2), (3,2)–(4,2), (4,2)–(5,1)
Figure 14.18 shows how LinePlotGUI, an improved version of the LinePlot program, displays the above (0,0) to (1,3) to ... to (5,1) line. In the interest of simplicity, there are no interval hash marks on the x and y axes. As you can perhaps guess, the shown x axis has six implied hash marks for the values 0, 1, 2, 3, 4, and 5. And the shown y axis has four implied hash marks for the values 0, 1, 2, and 3.
Pre-Written Software and the drawPolyLine Method
    Consider using bottom-up design.
In solving problems, it’s fairly common to take a top-down approach: Write the driver method first (main), then write the public methods that provide an interface to the outside world, then write the private helping methods. That approach frequently works fine, but it can sometimes lead to reinventing the wheel. If you used a pure top-down approach to imple- ment the LinePlotGUI program, you’d probably implement the line display as a sequence of
      drawLine method calls, one for each segment of the line (for a discussion of the drawLine method, see Chapter 5). Using drawLine would work, but it would require a loop and probably some debugging effort. The better approach is to dust off your Java API tome (http://java.sun.com/javase/6/docs/api/) and search for alternative line-drawing methods.
Lo and behold, there’s a line drawing method that does exactly what you want. The drawPolyline method draws a line by connecting a sequence of points. More specifically, the Graphic class’s drawPolyline method receives three parameters—xPixels, yPixels, and numOfPoints. The numOfPoints parameter holds the number of points in the line. The xPixels parameter holds an array
   








































































   616   617   618   619   620