Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a GUI with two text fields for inputting the dimensions of a rectangle. I

ID: 3554569 • Letter: C

Question

Create a GUI with two text fields for inputting the dimensions of a rectangle. Identify these two text fields as Length and Width with labels. Add a button that will read the text fields and cause the GUI to display the area and perimeter of the rectangle in labels. Display all outputs with two decimal places. Include another button that will reset the text fields and outputs. Finally, include at least two radiobuttons that can be used to set the color of the GUI window background. You choose the colors. Your GUI should exhibit good GUI layout and design

Explanation / Answer

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

public class RectangleGUI extends JFrame {

JLabel lengthL;
JLabel widthL;
JLabel areaL;   
JLabel perimeterL;

JTextField lengthTF;
JTextField widthTF;
JTextField areaTF;
JTextField perimeterTF;

JButton CalculateB;
JButton ExitB;

CalculateButtonHandler cbHandler;
ExitButtonHandler ebHandler;

public RectangleGUI()

{
setTitle("Area and Perimeter of a Rectangle");

lengthL = new JLabel("Enter the length: ", JLabel.RIGHT);
widthL = new JLabel ("Enter the width: ", JLabel.RIGHT);
areaL = new JLabel ("Area: ", JLabel.RIGHT);
perimeterL = new JLabel ("Perimeter: ", JLabel.RIGHT);

lengthTF = new JTextField(10);
widthTF = new JTextField (10);
areaTF = new JTextField (10);
perimeterTF = new JTextField (10);

CalculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
CalculateB.addActionListener(cbHandler);

ExitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
ExitB.addActionListener(ebHandler);

Container pane = getContentPane();
pane.setLayout(new GridLayout(5,2));

pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(perimeterL);
pane.add(perimeterTF);
pane.add(CalculateB);
pane.add(ExitB);

setSize(400,300);
setVisible(true);
}

public class CalculateButtonHandler implements ActionListener {

public void actionPerformed (ActionEvent e)
{
double l, w, area, peri;

l=Double.parseDouble(lengthTF.getText());
w=Double.parseDouble(widthTF.getText());

area=l*w;
peri=2*(l+w);

areaTF.setText("" + area);
perimeterTF.setText("" + peri);
}
}

public class ExitButtonHandler implements ActionListener {

public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}

public static void main(String[] args) {

RectangleGUI rectObject = new RectangleGUI();

}

}