java code please In algebra, we use f(x) = x^2 function to graph a parabola. You
ID: 3568632 • Letter: J
Question
java code please
In algebra, we use f(x) = x^2 function to graph a parabola. You will be using the Java Graphics class to draw a diagram for the function f(x) = x^ 2 on a GUI component.
The Graphics class provides the methods for drawing strings, lines, rectangles, ovals, arcs, polygons, and polylines. Think of a GUI component as a piece of paper and the Graphics object as a pencil or paintbrush. You can apply the methods in the Graphics class to draw graphics on a GUI component. To draw on a component, you need to define a class that extends JPanel and overrides its paintComponent method to specify what to draw. The signature of the paintComponent method is as follows:
protected void paintComponent(Graphics g)
Add points to a polygon p using the following loop:
double scaleFactor = 0.1;
for (int x=-100; x<=100; x++) {
p.addPoint(x+200, 200- (int)(scaleFactor *x *x));
}
Connect the points using g.drawPolyline(p.xpoints, p.ypoints, p.npoints) for a Graphics object g. p.xpoints returns an array of x-coordinates, p.ypoints an array of y-coordinates, and p.npoints the number of points in Polygon object p.
Directions
please post a screenshot of the running code
Explanation / Answer
//*******Parabola.java*************//
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Parabola extends JFrame {
public Parabola(String g){
super(g);
}
public static class GraphPanel extends JPanel{
@Override
protected void paintComponent(Graphics g){
g.drawLine(50,200,350,200);
g.drawString("x",360,200);
g.drawLine(200, 0, 200, 300);
g.drawString("y", 200, 310);
//draw x and y axes
Polygon p = new Polygon();
double scaleFactor=0.1;
for(int x=-100;x<=100;x++){
p.addPoint(x+200,200-(int)(scaleFactor*x*x));
//add points for the parabola
}
g.drawPolygon(p);
}
}
}
//******ParabolaDemo*******//
import javax.swing.JFrame;
/**
*
* Draw a parabola in JFrame, the function of this parabola is
* y=x^2
*
*/
public class ParabolaDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Parabola frame= new Parabola("Parabola");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
Parabola.GraphPanel g= new Parabola.GraphPanel();
frame.add(g);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.