[java]代码库
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Chp13_1 extends JFrame{
private JButton jisuan;
private JPanel panel1,panel2,panel3,panel4;
private JTextField field1,field2,field3;
private JLabel label1,label2,label3,label4;
private JTextArea area;
private Container container;
Chp13_1(){
super("计算一元二次方程的根");
container = getContentPane();
container.setLayout(new FlowLayout());
label4 = new JLabel("请依次输入一元二次方程的三个系数,并点击计算显示实根");
container.add(label4);
panel1 = new JPanel();
label1 = new JLabel("系数a");
field1 = new JTextField(10);
panel1.add(label1);
panel1.add(field1);
panel2 = new JPanel();
label2 = new JLabel("系数b");
field2 = new JTextField(10);
panel2.add(label2);
panel2.add(field2);
panel3 = new JPanel();
label3 = new JLabel("系数c");
field3 = new JTextField(10);
panel3.add(label3);
panel3.add(field3);
panel4 = new JPanel();
panel4.setLayout(new GridLayout(1,3,1,2));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
container.add(panel4);
jisuan = new JButton("计算");
jisuan.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event) {
double a = Double.parseDouble(field1.getText());
double b = Double.parseDouble(field2.getText());
double c = Double.parseDouble(field3.getText());
double deerta = b*b-4*a*c;
if(deerta < 0){
area.setText("无实根");
}else {
double x1 = (Math.sqrt(deerta)-b)/(2*a);
double x2 = (-Math.sqrt(deerta)-b)/(2*a);
area.setText("实根1 = "+x1+"\n实根2 = "+x2);
}
}
}
);
container.add(jisuan);
area = new JTextArea(10,15);
area.setText("该方程的实根为");
container.add(area);
setSize(500,400);
setVisible(true);
}
public static void main(String[] args) {
Chp13_1 application = new Chp13_1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}