In: Computer Science
(Display a Circle and Its Attributes) Write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumference. Use the following equations: diameter = 2 × radius, area = π × radius2, circumference = 2 × π × radius. Use the constant Math.PI for pi (π). All drawing should be done on a subclass of JPanel, and the results of the calculations should be displayed in a read-only JTextArea.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//RandomCircle.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class RandomCircle extends JFrame {
// panel to draw a circle (see CirclePanel class at the bottom)
private CirclePanel circle;
// text area to represent stats
private JTextArea stats;
// constructor to initialize the GUI
public RandomCircle() {
// will exit on close
setDefaultCloseOperation(EXIT_ON_CLOSE);
// initializing circle panel, with a random radius between 50 and 200
circle = new CirclePanel((int) (Math.random() * 151) + 50);
// and the read only text area
stats = new JTextArea();
stats.setEditable(false);
// finding area, circumference and diameter of circle
double area = Math.PI * circle.getRadius() * circle.getRadius();
double circumference = 2 * Math.PI * circle.getRadius();
int diameter = circle.getRadius() * 2;
// updating stats text area withg all these info
stats.setText(String.format(
"Area: %.2f\nRadius: %d\nDiameter: %d\nCircumference: %.2f",
area, circle.getRadius(), diameter, circumference));
// adding circle panel to the center and stats to the bottom
add(circle, BorderLayout.CENTER);
add(stats, BorderLayout.PAGE_END);
// using 500x500 size
setSize(500, 500);
// making window visible
setVisible(true);
}
public static void main(String[] args) {
// initializing GUI
new RandomCircle();
}
}
// CirclePanel class to draw a circle. should be placed in the same file
class CirclePanel extends JPanel {
// radius of circle
private int radius;
// constructor taking circle radius
public CirclePanel(int radius) {
this.radius = radius;
}
// returns the radius
public int getRadius() {
return radius;
}
// method to draw the circle whenever panel is updated
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// using gray color
g.setColor(Color.GRAY);
// drawing a filled circle centered at the center of the panel
g.fillOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
radius * 2, radius * 2);
}
}
/*OUTPUT*/