用Java实现以下功能: 当用户在图形化用户界面输入一个圆的半径时,程序将显示该圆的周长与面积,并画出该圆
时间: 2023-06-01 08:04:09 浏览: 63
以下是一个用Java实现该功能的例子:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CircleCalculator extends JPanel implements ActionListener {
private JTextField radiusField;
private JLabel perimeterLabel;
private JLabel areaLabel;
private JButton calculateButton;
private double radius;
public CircleCalculator() {
radiusField = new JTextField(10);
perimeterLabel = new JLabel("Perimeter: ");
areaLabel = new JLabel("Area: ");
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
add(new JLabel("Radius: "));
add(radiusField);
add(calculateButton);
add(perimeterLabel);
add(areaLabel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == calculateButton) {
String text = radiusField.getText();
if (text.equals("")) {
perimeterLabel.setText("Perimeter: ");
areaLabel.setText("Area: ");
repaint();
return;
}
try {
radius = Double.parseDouble(text);
double perimeter = 2 * Math.PI * radius;
double area = Math.PI * radius * radius;
perimeterLabel.setText("Perimeter: " + perimeter);
areaLabel.setText("Area: " + area);
repaint();
} catch (NumberFormatException ex) {
perimeterLabel.setText("Perimeter: ");
areaLabel.setText("Area: ");
repaint();
return;
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
if (radius > 0) {
int x = getWidth() / 2 - (int) radius;
int y = getHeight() / 2 - (int) radius;
int diameter = (int) (2 * radius);
g.drawOval(x, y, diameter, diameter);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Circle Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setContentPane(new CircleCalculator());
frame.setVisible(true);
}
}
```
该程序使用了一个JPanel作为图形化用户界面,包含一个文本框、两个标签和一个按钮。当用户输入圆的半径并点击“Calculate”按钮时,程序会计算圆的周长和面积,并在标签中显示出来。程序还会绘制出该圆形。
在程序的主函数中,创建了一个JFrame实例,并将该JPanel实例设置为其内容面板。最后,将该JFrame实例设置为可见。