GUI Rectangle - Java Sample Program

// This Java Program determines the area and
// perimeter of a rectangle.
import javax.swing.JOptionPane;
public class Rectangle
{
public static void main(String[] args)
{
double width, length, area, perimeter; //Line 1
String lengthStr, widthStr, outputStr; //Line 2

lengthStr =JOptionPane.showInputDialog("Enter the length: "); //Line 3
length = Double.parseDouble(lengthStr); //Line 4
widthStr =JOptionPane.showInputDialog("Enter the width: "); //Line 5
width = Double.parseDouble(widthStr); //Line 6
area = length * width; //Line 7
perimeter = 2 * (length + width); //Line 8

outputStr = "Length: " + length + "\n" +
"Width: " + width + "\n" +
"Area: " + area + " square units\n" +
"Perimeter: " + perimeter + " units\n"; //Line 9

JOptionPane.showMessageDialog(null, outputStr, "Rectangle",
JOptionPane.INFORMATION_MESSAGE); //Line 10

System.exit(0); //Line 11
}
}

//Sample Output


 The statements in Lines 1 and 2 declare various variables to manipulate the data. The statement in Line 3 displays the first dialog box of the sample run and prompts the user to enter the length of the rectangle.

 The entered length is assigned as a string to lengthStr. The statement in Line 4 retrieves the
length and stores it in the variable length.

The statement in Line 5 displays the second dialog box of the sample run and prompts the
user to enter the width of the rectangle. The entered width is assigned as a string to
widthStr. The statement in Line 6 retrieves the width and stores it in the variable width.

 The statement in Line 7 determines the area, and the statement in Line 8 determines the
perimeter of the rectangle. The statement in Line 9 creates the string containing the
desired output and assigns it to outputStr. The statement in Line 10 uses the output
dialog box to display the desired output, which is shown in the third dialog box of the

sample run. Finally, the statement in Line 11 terminates the program.

No comments: