A Class for Circles

 

Background.  Now we will develop some rather rudimentary classes to illustrate some of the principles and issues we have worked with so far.  Our first example relates to circles.  We keep it simple and don't really do any drawing.  But we will get a radius from a user and compute relevant things such as the area and the circumference.

Whether you are aware of it or not, the radius is the most salient measure related to a circle.  If you know it you should be able to find out just about anything else you want about the circle.  You may remember that one classic definition is it is the set of points in a plane that are equidistant from one center point.

So, ultimately, our circles will be represented by a single number in the computer.  They are not represented by a drawn circle.

Remember, it took three numbers to represent the time.  When we set the time we used computer syntax

setTime(hh,mm,ss)

It required some extra methods to cast this into the more familiar

hh:mm:ss

form.

You should call the following file Circle.java and save it in its own directory. Whether or not you want to create a package is up to you.  You will notice we sometimes make use of the this reference rather than referring to an instance of an object by its name.

 

import java.text.DecimalFormat;

public class Circle extends Object
{

private double radius;
final double PI = 3.14159;

public Circle( )
{

setCircle(0);

}


public Circle(double rad)
{

setCircle(rad);

}


public void setCircle(double rad)
{

radius = rad;

}

public void setRadius(double rad)
{

radius = rad;

}

public double getRadius( )
{

return radius;

}


public double computeArea( Circle input )
{

return PI * this.getRadius( ) * this.getRadius( );

}

public double computeCircumference( Circle input )
{

return 2 * PI * this.getRadius( );

}

public String toPrecisionFourString(double someNumber)
{

DecimalFormat precisionFour = new DecimalFormat("0.0000");
return precisionFour.format(someNumber);

}

}

 

You should compile this, likely with the more typical

javac Circle.java

We start with a discussion of the code and methods.

  • import java.text.DecimalFormat

  • the overall inclusive class is called Circle that extends Object

    • declare an instance variable double radius

    • declare a constant instance variable final double PI = 3.14159

 

  • define a constructor Circle( )

    • receives no arguments

    • uses a later method setRadius to initialize the radius to zero

 

  • define a constructor Circle( )

    • receives a single double precision argument rad

    • uses a later method setRadius to initialize the radius to rad

 

  • a setRadius( ) method is declared and developed
    • it receives a single double precision argument
      • rad for the radius
    • it assigns the instance variable radius equal to the rad that is passed

 

  • a getRadius( ) method is declared and developed
    • it receives no arguments
    • it returns the radius of the object

 

  • a computeArea( ) method is declared and developed
    • it receives one argument
      • an object of type Circle
    • it returns a double precision number representing the area of the circle
    • the area is computed using the constant PI times the radius squared
      • the radius is obtained using this.getRadius( )

 

  • a computeCircumference( ) method is declared and developed
    • it receives one argument
      • an object of type Circle
    • it returns a double precision number representing the circumference of the circle
    • the area is computed using 2 times the constant PI times the radius
      • the radius is obtained using this.getRadius( )

 

  • a toPrecisionFourString( ) method is declared and developed
    • it receives one double precision argument
    • it returns a String
    • it makes use of the DecimalFormat class in the text package to create a format that always has exactly four places after the decimal
    • it returns whatever double precision number was passed to it in this format as a string

 

Now you need the following CircleTestGUI.java to construct/instantiate a Circle object and work with it.

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CircleTestGUI extends JApplet implements ActionListener
{

// declare GUI components
JLabel lblRadiusInput;
JTextField txtRadiusInput;
JLabel lblEchoInput;
JTextField txtEchoInput;
JLabel lblAreaOutput;
JTextField txtAreaOutput;
JLabel lblCircumferenceOutput;
JTextField txtCircumferenceOutput;
JLabel lblClickToCompute;
JButton compute;
JPanel panInterface;
JPanel panGUI;
// declare two global instance variables related to inputs
boolean validInput;
double radiusInput = 0.0;

public void init( )
{

JPanel panInterface = new JPanel( );
panInterface.setLayout( new GridLayout(1, 1) );

panInterface = createGUI( );

setContentPane(panInterface);

}

public void actionPerformed(ActionEvent userClick)
{

// call method to obtain and validate input
// perform computations only if method returns true

if (validateInput( ))
{

if (userClick.getSource( ) == compute)
{

// instantiate an object of type Circle
// with the valid radius inputted by the user

Circle One = new Circle(radiusInput);
// echo back the input to the user
txtEchoInput.setText(Double.toString(One.getRadius( )));
// call the method to compute the area
// convert the numeric answer to a string with four places after the decimal point
// set the text in the appropriate JTextField

txtAreaOutput.setText(One.toPrecisionFourString(One.computeArea(One)));
// call the method to compute the circumference
// convert the numeric answer to a string with four places after the decimal point
// set the text in the appropriate JTextField

txtCircumferenceOutput.setText(One.toPrecisionFourString(One.computeCircumference(One)));
// a finalizer to free up memory allocation on Circle One
One = null;

}

}

}

public JPanel createGUI( )
{

JPanel panGUI = new JPanel( );
panGUI.setLayout( new GridLayout(5, 2, 5, 5) );

// developing input row
lblRadiusInput = new JLabel("Please input the radius: ", SwingConstants.RIGHT);
panGUI.add(lblRadiusInput);

txtRadiusInput = new JTextField(6);
panGUI.add(txtRadiusInput);

// developing command button row for program execution
lblClickToCompute = new JLabel("Click button to solve: ", SwingConstants.RIGHT);
panGUI.add(lblClickToCompute);

compute = new JButton("Compute");
compute.addActionListener(this);
panGUI.add(compute);

// developing output row for echo of the input
lblEchoInput = new JLabel("Echoing your input: ", SwingConstants.RIGHT);
panGUI.add(lblEchoInput);

txtEchoInput = new JTextField(5);
txtEchoInput.setEditable(false);
panGUI.add(txtEchoInput);

// developing output row for area
lblAreaOutput = new JLabel("The area of the circle: ", SwingConstants.RIGHT);
panGUI.add(lblAreaOutput);

txtAreaOutput = new JTextField(15);
txtAreaOutput.setEditable(false);
panGUI.add(txtAreaOutput);

// developing output row for circumference
lblCircumferenceOutput = new JLabel("The circumference of the circle: ", SwingConstants.RIGHT);
panGUI.add(lblCircumferenceOutput);

txtCircumferenceOutput = new JTextField(15);
txtCircumferenceOutput.setEditable(false);
panGUI.add(txtCircumferenceOutput);

return panGUI;

}

public boolean validateInput( )
{

validInput = true;

try
{

radiusInput = Double.parseDouble(txtRadiusInput.getText( ));

}

catch (NumberFormatException nfeDouble)
{

// give error message when input can't be parsed to double
JOptionPane.showMessageDialog(null, "You need to enter a number", "Input Error", JOptionPane.ERROR_MESSAGE);
// set boolean variable to false when
// received an invalid input
validInput = false;
// blanking out inputs and any previous outputs
// when input is invalid
txtRadiusInput.setText("");
txtEchoInput.setText("");
txtAreaOutput.setText("");
txtCircumferenceOutput.setText("");

}

return validInput;

}

}

 

You do not need to specify any special path in the compilation command.

javac CircleTestGUI.java

You should run this code and play with the GUI some before we dig into it.

The HTML file follows and should be called CircleTestGUI.html.

 

<html>
<applet code="CircleTestGUI.class" width=400 height=200>
</applet>
</html>

 

If you try to click on the command button and don't have an appropriate input you should see something like the following.

 

 

With an acceptable number in the radius text fields you should see something more like the following.

 

 

Notice the four decimal places on the area and the circumference.

Now we will discuss the code.

  • we need to import the javax.swing.* package
  • import java.awt.*
  • import java.awt.event

 

  • the overall inclusive class is called CircleTestGUI which extends JApplet and implements ActionListener
    • declare the GUI components
      • a label for the radius input = lblRadiusInput
      • a text field for the radius input = txtRadiusInput
      • a label for echoing the input = lblEchoInput
      • a text field for echoing the input = txtEchoInput
      • a label for outputting the area = lblAreaOutput
      • a text field for outputting the area = txtAreaOutput
      • a label for outputting the circumference = lblCircumferenceOutput
      • a text field for outputting the circumference = txtCircumferenceOutput
      • a label to tell the user to click the compute button = lblClickToCompute
      • a button to cause the program to compute = compute
      • a panel to contain the GUI called panInterface
      • a panel for developing the GUI called panGUI
    • declare the variables associated with user inputs
      • a boolean validInput to indicate whether the user's inputs pass the program's validity tests
      • initialize and declare a variable for the user's radius input = radiusInput

 

  • the init( ) method
    • instantiates a panel to be the panel that contains all the other panels called panInterface
    • sets its layout to be a grid with one row and one column
    • calls the methods to create the GUI called createGUI( )
    • sets the content pane for the applet to be panInterface

 

  • the actionPerformed( ) method
    • calls the validateInput( ) method to retrieve and validate the user's input
    • if the input is acceptable
      • determines the source of the user's click
      • if the user clicks the compute button
        • creates a new instance of a Circle object called One set by the user's inputs
        • echoes the input in the txtEchoInput text field
          • gets the radius using getRadius( )
          • sets the text using the built in setText( ) method
        • updates the display in the txtAreaOutput text field
          • calls the computeArea( ) method in the Circle class
          • uses the class method toPrecisionFourString( ) to format it for display
          • sets the text using the built in setText( ) method
        • updates the display in the txtCircumferenceOutput text field
          • calls the computeCircumference( ) method in the Circle class
          • uses the class method toPrecisionFourString( ) to format it for display
          • sets the text using the built in setText( ) method
      • destroys the Circle object called One

 

  • createGUI( )
    • creates the panel to contain the input components
    • sets the layout to a GridLayout with five rows and two columns
    • instantiates the appropriate JLabels and JTextFields
    • instantiates a JButton
    • sets editability properties appropriately
    • returns this panel to the calling location

 

  • the validateInput( ) method
    • initializes validInput to true
    • uses a try block to
      • get the text from txtRadiusInput
      • parse it as a double
    • uses a catch block if it can't be parsed as a double to
      • the errorMessage is displayed using the showMessageDialog( ) method of the JOptionPane class
      • set validInput to false
      • set the txtRadiusInput to blank
      • set the text of txtEchoInput to blank
      • set the text of txtAreaOutput to blank
      • set the text of txtCircumferenceOutput to blank
    • return the boolean validInput

 

We will do one more of these "simpler" classes before working some more sophisticated problems.