上机实践6 组件及事件处理
实验1 方程求根
实验目的
通过使用恰当的组件,给出计算一元二次方程根的GUI程序
实验要求
首先编写一个封装一元二次方程的类,然后再编写一个窗口。要求窗口使用三个文本框和一个文本区,为方程对象中的数据提供试图,其中三个文本框用来显示和更新方程对象的系数;文本区对象用来显示方程的根。窗口中有一个按钮,用户单击该按钮后,程序用文本框中的数据修改方程的系数,并将方程的根显示在文本区中。
程序模版
请按照模版要求,将【代码】替换为程序代码。
SquareEquation.java
public class SquareEquation
{ double a,b,c;
double
root1,root2;
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() throws
NoRealRootException,NoSquareEquationException
{ if(a!=0)
{ double disk=b*b-4*a*c;
if(disk>=0)
{ root1=(-b+Math.sqrt(disk))/(2*a);
}
else
{ throw new NoRealRootException("没有实根");
}
}
else
{
throw new NoRealRootException("不是二次方程");
}
return root1;
}
public
double getRootTwo() throws
NoRealRootException,NoSquareEquationException
{ if(a!=0)
{ double disk=b*b-4*a*c;
if(disk>=0)
{ root2=(-b-Math.sqrt(disk))/(2*a);
}
else
{ throw new NoRealRootException("没有实根");
}
}
else
{
throw new NoRealRootException("不是二次方程");
}
return root2;
}
}
class NoRealRootException extends Exception
{ String message;
NoRealRootException(String
s)
{ message=s;
}
public String
getMessage()
{ return message;
}
}
class NoSquareEquationException extends Exception
{ String message;
NoSquareEquationException(String s)
{ message=s;
}
public String
getMessage()
{ return message;
}
}
EquationFrame.java
import java.awt.*;
import java.awt.event.*;
public class EquationFrame extends Frame implements
ActionListener
{ SquareEquation equation;
TextField
textA,textB,textC;
TextArea showRoots;
Button controlButton;
public EquationFrame()
{ equation=new SquareEquation();
textA=new TextField(8);
textB=new TextField(8);
textC=new TextField(8);
showRoots=new TextArea();
controlButton=new Button("确定");
Panel pNorth=new Panel();
pNorth.add(new Label("二次项系数:"));
pNorth.add(textA);
pNorth.add(new Label("一次项系数:"));
pNorth.add(textB);
pNorth.add(new Label("常数项系数:"));
pNorth.add(textC);
pNorth.add(controlButton);
【代码1】 //当前窗口作为controlButton的ActionEvent事件的监视器
add(pNorth,BorderLayout.NORTH);
add(showRoots,BorderLayout.CENTER);
setBounds(100,100,630,160);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent
e)
{ try{
double
a=Double.parseDouble(【代码2】); //textA调用方法获取其中的文本
double b=Double.parseDouble(【代码3】);
//textB调用方法获取其中的文本 double c=Double.parseDouble(【代码4】); //
textC调用方法获取其中的文本
equation.setA(a);
equation.setB(b);
equation.setC(c);
textA.setText(""+a);
textB.setText(""+b);
textC.setText(""+c);
showRoots.append("\n 根:"+equation.getRootOne());
showRoots.append(" 根:"+equation.getRootTwo());
}
catch(Exception ex)
{ showRoots.append("\n"+ex+"\n");
}
}
}
EquationMainClass.java
public class EquationMainClass
{ public static void main(String args[])
{ EquationFrame frame=new EquationFrame();
}
}