//Plot.java import java.awt.*; import javax.swing.*; public class Plot extends JComponent { public Plot(Function f, double start, double end, double deltaX) { function = f; delta = deltaX; from = start; to = end; findRange(); // find max and min of f(x) setSize(200, 100); // default width, height } public void paint(Graphics g) { double x = from; double f_of_x = function.valueAt(x); while (x < to - delta) { double f_of_x_plus_delta; f_of_x_plus_delta = function.valueAt(x + delta); drawLine(g, x, f_of_x, x + delta, f_of_x_plus_delta); x = x + delta; f_of_x = f_of_x_plus_delta; } drawLine(g, x, f_of_x, to, function.valueAt(to)); } public void setBounds(int x, int y, int width, int height) { xScale = (width - 2) / (to - from); yScale = (height - 2) / (fmax - fmin); dim = new Dimension(width, height); super.setBounds(x, y, width, height); repaint(); } public Dimension getMinimumSize() { return dim; } public Dimension getPreferredSize() { return getMinimumSize(); } // scale and translate the points from the // user's coordinate space to Java's private void drawLine(Graphics g, double x1, double y1, double x2, double y2) { g.drawLine( (int)Math.round((x1 - from) * xScale), (int)Math.round((fmax - y1) * yScale), (int)Math.round((x2 - from) * xScale), (int)Math.round((fmax - y2) *yScale)); } // determine the minimum and maximum values of // f(x) with x varying between from and to private void findRange() { fmin = fmax = function.valueAt(from); for (double x = from + delta; x < to - delta; x = x + delta) { double f_of_x = function.valueAt(x); if (f_of_x < fmin) fmin = f_of_x; if (f_of_x > fmax) fmax = f_of_x; } } private Dimension dim; private double fmin, fmax; private double xScale, yScale; private double from, to, delta; private Function function; }