定义一个 EquationFrame类,具体代码如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EquationFrame extends JFrame implements ActionListener{
SquareEquation equation;
JTextField textA,textB,textC;
JTextArea showRoots;
JButton controlButton;
public EquationFrame(){
equation=new SquareEquation();
textA=new JTextField(8);
textB=new JTextField(8);
textC=new JTextField(8);
controlButton =new JButton("确定");
JPanel pNorth=new JPanel();
pNorth.add(new JLabel("二次项系数:"));
pNorth.add(textA);
pNorth.add(new JLabel("一次项系数:"));
pNorth.add(textB);
pNorth.add(new JLabel("常数项系数:"));
pNorth.add(textC);
pNorth.add(controlButton);
controlButton.addActionListener(this);
getContentPane().add(pNorth,BorderLayout.NORTH);
showRoots=new JTextArea();
JScrollPane scrollPane=new JScrollPane(showRoots);
getContentPane().add(scrollPane,BorderLayout.CENTER);
setSize(630,160);
Dimension scnSize=Toolkit.getDefaultToolkit().getDefaultToolkit().getScreenSize();
Dimension frmSize=this.getSize();
this.setLocation((scnSize.width-frmSize.width)/2,
(scnSize.height-frmSize.height)/2);
validate();
setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
try{
double a=Double.parseDouble(textA.getText());
double b=Double.parseDouble(textB.getText());
double c=Double.parseDouble(textC.getText());
equation.setA(a);
equation.setB(b);
equation.setC(c);
showRoots.append("根: "+equation.getRootOne());
showRoots.append(" 根:"+equation.getRootTwo()+"\n");
}catch(Exception ex)
{
showRoots.append(ex.getMessage()+"\n");
}
}
}
定义一个 EquationFrame类,具体代码如下:
public class SquareEquation {
double a,b,c;
public void setA(double a){
this.a=a;
}
public void setB(double b){
this.b=b;
}
public void setC(double c){
this.c=c;
}
public double getRootOne()
{
double disk=calculateValidDisk();
return (-b+Math.sqrt(disk))/(2*a);
}
public double getRootTwo(){
double disk=calculateValidDisk();
return (-b-Math.sqrt(disk))/(2*a);
}
private double calculateValidDisk()
{
if(a==0){
throw new EquationException("不是二次方程",
EquationException.NONE_EQUATION);
}
double disk=b*b-4*a*c;
if(disk<0)
{throw new EquationException("没有实根",
EquationException.NO_REAL_ROOT);
}
return disk;
}
}
class EquationException extends RuntimeException{
public static final int NONE_EQUATION=1;
public static final int NO_REAL_ROOT=2;
private int errorCode;
public EquationException(String msg,int errerCode)
{
super(msg);
this.errorCode=errorCode;
}
public int getErroeCode(){
return errorCode;
}
}
定义一个Text主类(!无此代码不可运行),具体代码如下:
public class Text {
public static void main(String args[])
{
new EquationFrame();
}
}