Program: Grapher

Grapher is a simple program to read a table of numbers and graph them. The input format is two or more lines that each contain an X and a Y value. The output is an on-screen display that can also be printed. Figure 12-7 shows the results of running it with the following simple data; the first column is the X coordinate and the second is the Y coordinate of each point. The program scales the data to fit the window.

1.5  5
1.7  6
1.8  8
2.2  7
Grapher in action

Figure 12-7. Grapher in action

Example 12-8 shows the code.

Example 12-8. Grapher.java

import com.darwinsys.util.Debug; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.util.*; /** Simple Graphing program. */ public class Grapher extends JPanel { /** Multiplier for range to allow room for a border */ public final static float BORDERFACTOR = 1.1f; /* Small inner class to hold x, y. Called Apoint to differentiate * from java.awt.Point. */ class Apoint { float x; float y; public String toString( ) { return "Apoint("+x+","+y+")"; } } /** The list of Apoint points. */ protected Vector data; /** The minimum and maximum X values */ protected float minx = Integer.MAX_VALUE, maxx = Integer.MIN_VALUE; /** The minimum and maximum Y values */ protected float miny = Integer.MAX_VALUE, maxy = Integer.MIN_VALUE; /** The number of data points */ protected int n; /** The range of X and Y values */ protected ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.