This is a exercise that i found in a book on java. I am not able to solve it.
public abstract class AbstractDrawFunction extends JPanel {
/** Polygon to hold the points */
private Polygon p = new Polygon();
protected AbstractDrawFunction () {
drawFunction();
}
/** Return the y-coordinate */
abstract double f(double x);
/** Obtain points for x-coordinates 100, 101, ..., 300 */
public void drawFunction() {
for (int x = -100; x <= 100; x++) {
p.addPoint(x + 200, 200 - (int)f(x));
}
}
/** Implement paintComponent to draw axes, labels, and
* connecting points
*/
protected void paintComponent(Graphics g) {
// To be completed by you
}
}
Test the class with the following functions:
f(x) = x2;
f(x) = sin(x);
f(x) = cos(x);
f(x) = tan(x);
f(x) = cos(x) + 5sin(x);
f(x) = 5cos(x) + sin(x);
f(x) = log(x) + x2;
For each function, create a class that extends the AbstractDrawFunction
class and implements the f method.
Implementing the subclasses is the easy part. Simply extend the class and implement the method; I suppose you already know and understand how to do this. If not, look up “derived classes” in your book.
The
paintComponentpart is a little harder, but only if it assumes that you scale the function to scale. It looks like the method should draw the graph in a 200 x 200 window, with the function ranging from -100 to 100. So no scaling, but you won’t see much of your sine and cosine functions.The fact that you don’t have to scale also means that drawing the axes is easy; note that the coordinate system runs from -100 to 100, that should give you enough clues.
Take care with
tan! It is not defined for all the input values. The same holds for one of the other functions, and that’s probably why they’re in the exercise.There is a little pitfall in that the method uses
Polygon. APolygoncan simple be drawn with a call toGraphics.drawPolygon, but that method will close it: the last point will be connected with the first.There are some workarounds for this, like adding extra points and forcing that extra line to be drawn exactly over an axis. But they won’t work for all formulae, and I don’t think it’s what you’re supposed to be working on. The exercise probably just uses
Polygonso you can calldrawPolygonfor the actual rendering.To add the JPanel to the JFrame, use
JFrame.add( subclass )orJFrame.setContentPane( subclass ).