Hey Guys,
This is my first program where I have used JLabel and JText. Im trying to create a program that will solve a simple quadratic equation. I have the program to the point where it will solve the equation, I just cant get it to display in the window. Any suggestion on how to get this to display?? Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class QuadraticEquationWindow extends JFrame
implements ActionListener
{
JTextField inputa, inputb, inputc, displayroot1, displayroot2;
public QuadraticEquationWindow ()
{
super("Quadratic Equation Solver");
JLabel labela= new JLabel("A: ", SwingConstants.RIGHT);
inputa= new JTextField(5);
JLabel labelb= new JLabel("B: ", SwingConstants.RIGHT);
inputb= new JTextField(5);
JLabel labelc= new JLabel("C: ", SwingConstants.RIGHT);
inputc= new JTextField(5);
JLabel labelroot1= new JLabel("X=", SwingConstants.RIGHT);
displayroot1= new JTextField(5);
displayroot1.setEditable(false);
JButton go= new JButton("Compute");
go.addActionListener(this);
Container a= getContentPane();
a.setBackground(Color.white);
JPanel p= new JPanel();
p.setLayout(new GridLayout(5, 1, 5, 5));
p.add(labela);
p.add(inputa);
p.add(labelb);
p.add(inputb);
p.add(labelc);
p.add(inputc);
p.add(labelroot1);
p.add(displayroot1);
a.add(p, BorderLayout.CENTER);
a.add(go, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
int a= Integer.parseInt(inputa.getText());
int b= Integer.parseInt(inputb.getText());
int c= Integer.parseInt(inputc.getText());
double root1= calculateQuadratic(a, b, c);
double root2= calculateQuadratic(a, b, c);
DecimalFormat df = new DecimalFormat("00000000.00000000");
displayroot1.setText(df.format(root1+" and "+root2));
}
private double calculateQuadratic(int a, int b, int c)
{
double b2, b3, root1, root2, h, h1, h2, h3, h4, h5, i1, i2;
b2= (-b);
b3= Math.pow(b,2);
h= (b3-4*a*c);
h1= (2*a);
if(h>0)
{
h2= Math.pow(h, .5);
h3= b2+h2;
h4= b2-h2;
root1= h3/h1;
root2= h4/h1;
return root1+root2;
}
if(h==0)
{
h2= 0;
h3= h2+b2;
root1= h3/h1;
root2= b2/h1;
return root1+root2;
}
else
{
h2= Math.abs(h);
h3= Math.pow(h2, .5);
h4= b2+h3;
root1= h4/h1;
h5= b2- h3;
i1= h5/h1;
i2= b2/h1;
root1= i1+i2;
root2= i1-i2;
return root1+root2;
}
}
public static void main(String[] args)
{
QuadraticEquationWindow w= new QuadraticEquationWindow ();
w.setBounds(300, 300, 300, 250);
w.setDefaultCloseOperation(EXIT_ON_CLOSE);
w.setVisible(true);
}
}