We can abstract the graph of this function in useful ways by defining a new class for it:
class Function {
double getValue(double x){ return x*x;}
}
If we add an instance of this class to the CartesianComponent
class CartesianComponent extends matti.gui.CComponent{ Function
a_function = new Function(); }
Then the draw method of the CartesianComponent looks like
void draw(Graphics g) {
g.setColor(Color.red);
CPoint position = new CPoint(-10, a_function.getValue(-10));
g.moveTo(position);
double dx = .05;
for(double x = -10; x <= 10; x = x + dx){
position = new CPoint(x, a_function.getValue(x));
g.lineTo(position);
}
This abstraction allows us to make our applet more elaborate:
First we'll add some variables (members) to our function, and then use them
in the getValue method:
class Function {
double a;
double b;
double getValue(double x){ return a*(x-b)*(x-b);}
}
Now will connect these variables to the sliders
with a method in the ExampleApplet
like:
void sliderMoved(Slider src) {
double v = src.getSliderValue();
}
Here is the result:
Complete source code for this Example