Need help writing a Java code to display a graph of the quadratic equation. To m
ID: 3902282 • Letter: N
Question
Need help writing a Java code to display a graph of the quadratic equation. To make a JPanel of some reasonable size in a window theb turn it into a GPanel, and put the calls into the paint method of the GPanel.
Hints: create a method in GPanel to set and remember the QuadObject object(with a name like setQO, perhaps). Save a copy of the (pointer to) the QuadObject the same way the sample GPanel saves the Graphics object g. Then you can graph x against quadObject.f(x).
Make you GPanel invisible when it is first created and added to the graphics environment. In the event handler for the DrawGraph button:
1. Figure out xmin..ymax by calculating them using Double.parseDouble from their appropriate text fields
2. Use a method in GPanel to pass in those four xmin..ymax values.
3. Create your QuadObject object by reading text fields for a, b, and c.
4. Pass in that QuadObject object to the GPanel.
5. Figure out how to tell the GPanel its width and height, or make it "read" its own height and width using getHeight() and getWidth() methods it inherits from JPanel
6. Make the GPanel visible by using the setVisible() method inherited from JPanel
Xmin -10.0 Xmax 10.0 Ymin 10.0 Ymax 10.0 A 2 B -14 C 24 Draw GraphExplanation / Answer
// the code is almost completed you can run it once,
// one problem remains, that the graph location on the axes is not correct, I am rectifying that now
// output is attached
// plz comment if you need any clarification
// hit like if you liked it
// CODE
package chegg.june;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.TextAttribute;
import java.awt.geom.QuadCurve2D;
import java.text.AttributedString;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
// Driver class to test the QuadWindow class
public class Chegg330 {
public static void main(String... args) {
QuadWindow qw = new QuadWindow("Quadratic ");
}
}
class QuadWindow extends JFrame{
int A, B, C;
int xMin, yMin;
int xMax, yMax;
private JTextField tfA, tfB, tfC, tfXMin, tfXMax, tfYMax, tfYMin;
JPanel hiddenPanel;
GPanel graphPanel;
public QuadWindow(String title) {
super(title);
init();
}
private void init() {
setLayout(null); // remove layout of the panel
//setSize(400, 500); // set the size of the window
setBounds(0, 0, 600, 500);
JLabel message = new QLabel(0, 0);
message.setBounds(225, 0, 100, 50);
add(message); // set the quadratic message formula as the first row
graphPanel = new GPanel(-10, -10, 10, 10, new int[]{1, 2, 3}, new int[]{5, -1, 7});
graphPanel.setBounds(181, 51, 400, 400);
add(graphPanel);
JLabel lblxMin = new JLabel("X Min");
lblxMin.setBounds(50, 50, 50, 30);
add(lblxMin);
tfXMin = new JTextField("");
tfXMin.setBounds(101, 50, 50, 30);
add(tfXMin);
JLabel lblyMin = new JLabel("Y Min");
lblyMin.setBounds(50, 80, 50, 30);
add(lblyMin);
tfYMin = new JTextField("");
tfYMin.setBounds(101, 80, 50, 30);
add(tfYMin);
JLabel lblxMax = new JLabel("X Max");
lblxMax.setBounds(50, 110, 50, 30);
add(lblxMax);
tfXMax = new JTextField("");
tfXMax.setBounds(101, 110, 50, 30);
add(tfXMax);
JLabel lblyMax = new JLabel("Y Max");
lblyMax.setBounds(50, 140, 50, 30);
add(lblyMax);
tfYMax = new JTextField("");
tfYMax.setBounds(101, 140, 50, 30);
add(tfYMax);
JLabel lblA = new JLabel("A");
lblA.setBounds(50, 170, 50, 30);
add(lblA);
tfA = new JTextField("");
tfA.setBounds(101, 170, 50, 30);
add(tfA);
JLabel lblB = new JLabel("B");
lblB.setBounds(50, 200, 50, 30);
add(lblB);
tfB = new JTextField("");
tfB.setBounds(101, 200, 50, 30);
add(tfB);
JLabel lblC = new JLabel("C");
lblC.setBounds(50, 230, 50, 30);
add(lblC);
tfC = new JTextField("");
tfC.setBounds(101, 230, 50, 30);
add(tfC);
JButton btnX = new JButton("Draw Graph");
btnX.setBounds(225, 410, 150, 40);
add(btnX);
// add action listener to the button Calculate f(X) when clicked
btnX.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
// First get the values of A, B, C and X
A = Integer.parseInt(tfA.getText());
B = Integer.parseInt(tfB.getText());
C = Integer.parseInt(tfC.getText());
xMin = Integer.parseInt(tfXMin.getText());
yMin = Integer.parseInt(tfYMin.getText());
xMax = Integer.parseInt(tfXMax.getText());
yMax = Integer.parseInt(tfYMax.getText());
evalQuadratic();
} catch(Exception ex) {
System.out.println("Enter valid values for A, B, C and x, y coordinates");
}
}
});
setResizable(false); // make the window not resizable
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the exit on close
setLocationRelativeTo(null); // set the window at the middle
setVisible(true); // make it visible
}
private double evalQuadratic() {
if(discriminant(A, B, C) < 0) { // check if the roots are imaginary
// if so, display them in an error dialog
JOptionPane.showMessageDialog(null, this.getImaginaryRoots(A, B, C), "QE has imaginary roots", 0);
return Double.MAX_VALUE;
}
// first find the roots of the equation
int r1 = getRoot(A, B, C, 1);
int r2 = getRoot(A, B, C, 2);
r1 = Math.max(r1, r2);
r2 = Math.min(r1, r2);
// to get the curve, we shoud have 3 points
// we will generate those three points from the roots
// two points are the start and end of the graph
// and the middle point
int xCoords[] = new int[3];
int yCoords[] = new int[3];
xCoords[0] = Math.min(r1+2, xMax);
yCoords[0] = evalQuadratic(A, B, C, xCoords[0]);
xCoords[1] = (r1+r2)/2;
yCoords[1] = evalQuadratic(A, B, C, xCoords[1]);
xCoords[2] = Math.max(r1-2, xMin);
yCoords[2] = evalQuadratic(A, B, C, xCoords[2]);
// now set this bounds and curve arrays to the same fields in the GPanel
graphPanel.setFields(xMin, yMin, xMax, yMax, xCoords, yCoords);
repaint();
return 0;
}
private int evalQuadratic(int A, int B, int C, int X) {
return (A*X*X) + (B*X) + C; // return ax^2+bx+c
}
private int discriminant(int A, int B, int C) {
return (B*B) - (4*A*C); // return b^2 - 4ac
}
private int getRoot(int A, int B, int C, int i) {
int disc = discriminant(A, B, C); // calculate f(X) for given X
if(disc >= 0 ) {
int root;
if(i == 1) {
root = ((-B) + (int)Math.sqrt(disc) )/ (2*A);
} else {
root = ((-B) - (int)Math.sqrt(disc) )/ (2*A);
}
return root;
} else {
return -1;
}
}
private String getImaginaryRoots(int A, int B, int C) {
double disc = -discriminant(A, B, C);
double t2 = (Math.sqrt(disc) ) / (2*A);
double t1 = (-B) / (2*A);
return "("+t1+" +/- "+t2+"i)"; // return the imaginary roots
}
}
/**
* This class extends JLabel, it takes as arguments 3 integers A, B, C which are
* Co-efficients of a Quadratic Equation QE.
* Then it will create a
* @author ram bablu
*/
class QLabel extends JLabel {
private final int w, h; // width and height
// Constructor
public QLabel(int w, int h) {
// this label draws the equation w px away from the origin horizontally
// and h px ayaw from origin vertically
this.w = w;
this.h = h;
}
/**
* Overrides paint method in JLabel
* @param g
*/
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g; // create a 2D graphics object
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
AttributedString as1 = new AttributedString("-(B)±|(B)2-4(A)(C)"); // create an attributed string
as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 9, 10); // set the square in formula(B^2 - 4*A*C), as a superscript
g2d.drawLine(w+32, h+9, w+93, h+9); // draw a line to depict the square line
g2d.drawString(as1.getIterator(), w+5, h+20); // draw string to dipict the (-B)±sqrt(B^2 - 4AC)
g2d.drawLine(w+5, h+25, w+95, h+25); // draw a line to represent the divided by line of the equation
g2d.drawString("2(A)", w+40, h+40); // draw 2A in the formula in the denumerator
//g2d.drawRect(w+0, h+0, 100, 55); // draw a border to the label so that it is clearly visible with bounds
}
}
class GPanel extends JPanel {
private int xMin, yMin;
private int xMax, yMax;
private int xCoords[];
private int yCoords[];
public GPanel() {
this(-10, -10, 10, 10, null, null);
}
public GPanel(int xMin, int yMin, int xMax, int yMax, int xCoords[], int yCoords[]) {
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.xCoords = xCoords;
this.yCoords = yCoords;
}
public void setFields(int xMin, int yMin, int xMax, int yMax, int xCoords[], int yCoords[]) {
this.xMin = xMin;
this.yMin = yMin;
this.xMax = xMax;
this.yMax = yMax;
this.xCoords = xCoords;
this.yCoords = yCoords;
repaint();
}
@Override
public void paint(Graphics g) {
// width, height and padding for the coordinate axes
int width = 350;
int height= 350;
int padding = 0;
Graphics2D g2d = (Graphics2D) g; // create a 2D graphics object
g2d.drawRect(0, 0, width, height); // draw a rectangle at the borders of the panel
g2d.drawLine(width/2, 0+padding, width/2, height-padding);
g2d.drawLine(0+padding, height/2, width-padding, height/2);
int originX = width/2;
int originY = height/2;
int xDiv = Math.max(Math.abs(xMin), Math.abs(xMax));
int yDiv = Math.max(Math.abs(yMin), Math.abs(yMax));
int xFactor = originX / xDiv;
int yFactor = originY / yDiv;
for(int i = 1; i <= xDiv; i++) {
g2d.fillRect(originX+(xFactor*i), originY, 1, 4); // fill xPoints
g2d.fillRect(originX-(xFactor*i), originY, 1, 4); // fill xPoints
g2d.fillRect(originX, originY+(yFactor*i), 4, 1); // fill xPoints
g2d.fillRect(originX, originY-(yFactor*i), 4, 1); // fill xPoints
}
if(xCoords != null && yCoords != null) {
System.out.println("Origin = "+originX +", "+ originY);
System.out.println("Pair 1 = "+(originX+(xFactor*xCoords[0])) +", "+ (originY-(yFactor*yCoords[0])));
System.out.println("Pair 1 = "+(originX+(xFactor*xCoords[1])) +", "+ (originY-(yFactor*yCoords[1])));
System.out.println("Pair 1 = "+(originX+(xFactor*xCoords[2])) +", "+ (originY-(yFactor*yCoords[2])));
QuadCurve2D.Double curve = new QuadCurve2D.Double(originX+(xFactor*xCoords[0]), originY-(yFactor*yCoords[0]), // point 1
originX+(xFactor*xCoords[1]), originY-(yFactor*yCoords[1]), // middle point
originX+(xFactor*xCoords[2]), originY-(yFactor*yCoords[2]) // point 2
);
g2d.draw(curve);
}
}
}
// OUTPUT
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.