( Plot functions using abstract methods ) Write an abstract class that draws the
ID: 3535181 • Letter: #
Question
(Plot functions using abstract methods) Write an abstract class that draws the diagram for a function. The class is defined as follows:
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));
}
}
@Override /** Draw axes, labels, and connect points */
protected void paintComponent(Graphics g) {
// To be completed by you
}
}
Test the class with the following functions:
a. f(x) = x2;
b. f(x) = sin(x);
c. f(x) = cos(x);
d. f(x) = tan(x);
e. f(x) = cos(x) + 5sin(x);
f. f(x) = 5cos(x) + sin(x);
g. f(x) = log(x) + x2;
For each function, create a class that extends the AbstractDrawFunction class and implement the f method. The result of the program (see the attachment) displays the drawing for the first three functions.
Explanation / Answer
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 paintComponent part 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. A Polygon can 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 Polygon so you can call drawPolygon for the actual rendering.
To add the JPanel to the JFrame, use JFrame.add( subclass ) or JFrame.setContentPane( subclass ).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.