【发布时间】:2020-06-27 17:26:57
【问题描述】:
我正在尝试编写一个计算圆的面积和周长的程序。该程序应该有两个按钮。一种用于计算过程。另一个是关闭程序。我在实现 ActionListener 时遗漏了一些东西。你能帮帮我吗?
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class Circle extends JFrame {
private JLabel radiusLabel, areaLabel, perimeterLabel ;
private JTextField radiusText, areaText, perimeterText;
private JButton calculateButton, exitButton;
private CalculateButtonHandler calculateButtonHandler;
private ExitButtonHandler exitButtonHandler;
public Circle(){
setLayout(new FlowLayout());
radiusLabel = new JLabel("radius");
areaLabel = new JLabel("Area");
perimeterLabel = new JLabel("Perimeter");
radiusText = new JTextField(10);
areaText = new JTextField(10);
perimeterText = new JTextField(10);
calculateButton = new JButton("Calculate") ;
calculateButtonHandler = new CalculateButtonHandler();
calculateButtonHandler.addActionListener(calculateButtonHandler);
exitButton = new JButton("Close") ;
exitButton.addActionListener(exitButtonHandler);
setTitle("Area and Perimeter of a circle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
pane.add(radiusLabel);
pane.add(radiusText);
pane.add(areaLabel);
pane.add(areaText);
pane.add(perimeterLabel);
pane.add(perimeterText);
pane.add(calculateButton);
pane.add(exitButton);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class CalculateButtonHandler implements ActionListener{
public CalculateButtonHandler(ActionEvent e) {
double radius, area, perimeter ;
radius = Double.parseDouble(radiusText.getText());
area = radius * radius * 3.14 ;
perimeter = 2 * radius * 3.14 ;
areaText.setText("" + area);
perimeterText.setText("" + perimeter);
}
}
private class ExitButtonHandler implements ActionListener {
public ExitButtonHandler() {
System.exit(0);
}
}
public static void main(String[] args) {
Circle c = Circle();
}
}
【问题讨论】:
-
上述代码无法编译。您是否忽略了编译错误?使固定。他们。首先。
-
我知道。这就是我在发送问题前两个小时一直在尝试做的事情。
-
“我做的每一件事都正确..” 不是你在编译器报告错误时写的。 你应该写的(或而是复制/粘贴)是第一个(有多个)编译错误!
-
"如果我按照您的要求进行复制/粘贴,那么为什么会出现编译错误?。" 您是否看到...之间有任何联系。"如果我吃了一根香蕉,那为什么我的苹果会从树上掉下来?”。 不是吗?你写的那组词有同样多的逻辑,所以..我无法提供答案。 “我想我没有强迫你帮助我”这是真的。它支持这样一个概念,即如果你猜的次数足够多,你最终肯定是对的——如果只是由于随机机会的话。也许如果你再猜 763 次,你可能会用上面那个非常随机的代码解决多个问题。祝你好运!
-
@JavaBiggener,我想我没有强迫你帮助我 - 所以当你被要求发布一个更好的问题和更完整的信息时,你有时间发表评论吗?然而,您在一个多小时前已经得到了解决至少一些问题的答案,而您没有时间“接受”答案,甚至没有评论该建议是否有帮助?祝你未来的问题好运。
标签: java swing jframe actionlistener