这是我的完整源代码。
好像我无法获得输出。我可以成功获得用户界面,但是当我输入任何数字以获取球体的表面积和体积时,我无法获得确切的答案。我不知道是否弄乱了公式,还是事件处理代码出了点问题。
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Sphere extends JFrame implements ActionListener {
private JLabel radius, result;
private JTextField tfRadius, tfResult;
private JButton btnArea, btnVol;
private JPanel p1, p2;
public static void main(String[] args) {
Sphere S = new Sphere();
S.setSize(300, 150);
S.setVisible(true);
S.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Sphere() {
setTitle("Sphere");
setLayout(new BorderLayout());
radius = new JLabel("Radius");
result = new JLabel("Result");
tfRadius = new JTextField(10);
tfResult = new JTextField(10);
tfResult.setEditable(false);
btnArea = new JButton("Surface Area");
btnVol = new JButton("Volume");
p1 = new JPanel();
p1.setLayout(new GridLayout(2, 2, 2, 2));
p1.add(radius);
p1.add(tfRadius);
p1.add(result);
p1.add(tfResult);
p2 = new JPanel();
p2.add(btnArea);
p2.add(btnVol);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.SOUTH);
btnArea.addActionListener(this);
btnVol.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
DecimalFormat df = new DecimalFormat("0.0000");
double result = 0;
//double pi = 3.142; before I edited.
double radius = Double.parseDouble(tfRadius.getText());
//action from the respective button
if(e.getSource() == btnArea) {
result = 4 * (Math.PI * Math.pow(radius, 2)); //edited from pi to Math.pi
} else if (e.getSource() == btnVol) {
result = 4.0/3.0 * (Math.PI * Math.pow(radius, 3)); //edited from 1.333 to 4.0/3.0
}
tfResult.setText(String.valueOf(df.format(result)));
}
}