Java语言,用Swing组件编写程序,要求输入圆的半径r,求圆的面积?

用swing组件编写
2025-01-06 13:16:21
推荐回答(2个)
回答1:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormat;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Test {

JFrame frame = new JFrame("求圆的面积");
JLabel info = new JLabel("请输入圆的半径:");
JTextField rField = new JTextField();
JLabel result = new JLabel();

public void init() {
frame.setLayout(null);
frame.setSize(280, 100);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

info.setBounds(10, 10, 100, 30);
rField.setBounds(110, 15, 150, 20);
result.setBounds(30, 40, 220, 30);
frame.add(info);
frame.add(rField);
frame.add(result);
rField.addKeyListener(new KeyListener() {

public void keyPressed(KeyEvent e) {
}

public void keyReleased(KeyEvent e) {
double r = 0;
try {
r = Double.parseDouble(rField.getText());
} catch (NumberFormatException n) {
String txt = rField.getText();
if (!txt.equals("")) {
rField.setText(changeTxt(txt));
} else {
result.setText("");
}
return;
}
DecimalFormat format = new DecimalFormat("#0.00");
String area = format.format(Math.pow(Math.PI * r, 2));
result.setText("圆的面积: " + area);
}

public void keyTyped(KeyEvent e) {
}

});
}

public String changeTxt(String txt) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < txt.length(); i++) {
int n = (int) txt.charAt(i);
if (n >= 48 && n <= 57 || n == 46) {
s.append(txt.charAt(i));
}
}
return s.toString();
}

public static void main(String[] args) {
new Test().init();
}
}

回答2:

Swing是GUI包,根据你的问题,不需要用这个类包啊!
import java.math.*;
public class exp7
{
private double radius;
public exp7(double r)
{
this.radius=r;
}

public double calculateArea()
{
double s=Math.PI*radius*radius;
return s;
}

public static void main(String[] args)
{
exp7 t =new exp7(5.0);
System.out.println("圆的面积为:"+ t.calculateArea());
}
}