Write a program that displays a circle of given size and calculates and displays
ID: 673492 • Letter: W
Question
Write a program that displays a circle of given size and calculates and displays the area, radius, diameter, and circumference. Use the following equations:
diameter = 2(radius)
area = (Math.PI)(radius)(radius)
circumference = 2(Math.PI)(radius)
The user should be able to alter the radius with a JSlider. The program should work for radii in the range of 100 to 200. As the radius changes, the diameter, area, and circumference should be updated and displayed. The initial radius should be 150. All the drawing should be done on a subclass of JPanel, and the results of the calculations should be displayed in a read-only JTextArea.
Note:
1. You need to write your own subclass of JPanel that implements the dedicated drawing area in the application. However, for this assignment, do not write the JPanel subclass in a separate file. Include it in your application file as a separate class but make sure you DO NOT use the access modifier public for the JPanel class (remember, you can only have ONE public class per file). You should name this file HW2.java
Explanation / Answer
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Circle1 extends JFrame { private CircleCanvas theCanvas; private JTextArea display; public Circle1() { super( "Circle1" ); theCanvas = new CircleCanvas(); display = new JTextArea( 5, 30 ); display.setText( "The Radius is: " + theCanvas.getRadius() + " The Diameter is: " + theCanvas.getDiameter() + " The Area is: " + theCanvas.getArea() + " The Circumference is: " + theCanvas.getCircumference() ); //setLayout( new BorderLayout() ); getContentPane().add( theCanvas, BorderLayout.CENTER ); getContentPane().add( display, BorderLayout.SOUTH ); setSize( 200, 200 ); show(); } public static void main( String args[] ) { Circle1 app = new Circle1(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } class CircleCanvas extends JPanel { private int radius; public CircleCanvas() { radius = ( int )( 1 + Math.random() * 100 ); setSize( 100, 100 ); } public void paintComponent( Graphics g ) { g.drawOval( 0, 0, radius, radius ); } public int getDiameter() { return ( 2 * radius ); } public int getCircumference() { return ( int )( 2 * Math.PI * radius ); } public int getArea() { return ( int )( radius * radius * Math.PI ); } public int getRadius() { return radius; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.