我正在尝试创建一个图形圆计算器程序,该程序允许用户输入圆的直径,生成的输出在框架中显示圆的表示以及半径、周长和直径。我使用System.out.println()
命令来确保这些值被接受、计算和存储。但是,我无法让框架/组件从这些相同的变量中提取值,从而导致椭圆大小为 0x0,并且所有数据都表示为 0.0。
您能提供的任何帮助将不胜感激。程序代码如下。
package javaconcepts;
import java.awt.*;
import java.awt.geom.*;
import java.util.Scanner;
import javax.swing.*;
public class CircleComponent extends JComponent
{
private String input;
private float value;
private float radius;
private float circ;
private float area;
private static final long serialVersionUID = 1L;
public CircleComponent()
{
}
public void circleCalcValues()
{
System.out.println("Welcome to the Circle Graphical Calculator.");
System.out.println();
while(true)
{
System.out.print("Please enter the diameter's value (in pixels): ");
Scanner in = new Scanner(System.in);
input = in.next();
if(input.equals("done"))
{
System.out.println();
break;
}
value = (Float.valueOf(input));
System.out.println(value);
calculate();
System.out.println(radius + ", " + circ + ", " + area);
draw();
System.out.println();
System.out.println("Results are available in window.");
System.out.println();
}
System.out.println("OK.");
System.exit(0);
}
private void calculate()
{
radius = (value / 2);
circ = (float)(value * Math.PI);
area = (float)(Math.PI * Math.pow(value, 2));
}
private void draw()
{
JFrame frame = new JFrame();
frame.setSize(640, 480);
frame.setTitle("Circle Graphical Calculator: Result");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
CircleComponent component = new CircleComponent();
frame.add(component);
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Float output = new Ellipse2D.Float(100, 100, value, value);
g2.setColor(Color.BLACK);
g2.draw(output);
g2.setPaint(Color.WHITE);
g2.fill(output);
g2.setColor(Color.BLACK);
g2.drawString("Diameter: " + value + ", Radius: " + radius + ", Circumference: " + circ + ", Area: " + area, 50, 50);
}
}