4) Assume the existence of the following Java GUI application. There are two tex
ID: 641733 • Letter: 4
Question
4) Assume the existence of the following Java GUI application. There are two text fields for user input. The first JTextField variable is named radius and is used to input a radius value. The second JTextField variable named height is used to input a height value. All input values and calculations use floating point values. The user clicks a JButton to perform a calculation. One JButton called area causes the program to calculate and display the surface area of a cylinder, A = 2 * pi * r * r + 2 * pi * r * h. Another JButton called volume causes the program to calculate the volume of the cylinder, volume = pi * r * r * h. The result of the selected calculation is displayed in an output text area variable named output. The output string should say something like this: "Surface area of a cylinder with radius 1 and height 1 is 12.57." The output should display two digits after the decimal point. Clicking one of the buttons generates the event which causes the program to do the selected calculation and update the output area. Assume the user interface has already been implemented and the member variables listed above exist. Your job is to write the ButtonHandler inner class which handles the events from the two buttons, does the requested calculation and displays the appropriate result.
Explanation / Answer
Comment if you have any doubts.
class ButtonHandler implements ActionListener
{
//method that is called when button is clicked.
public void actionPerformed(ActionEvent ae) {
//if the button clicked is area
double r=Double.parseDouble(radius.getText());
double h=Double.parseDouble(height.getText());
if(ae.getSource()==area)
{
//calculate the area
double a=2*pi*r*r+2*pi*r*h;
//set the textarea to the following
output.setText("Surface area of cylinder with radius "+r+" and height "+h+" is "+(int)(a*100)/100.0);
}
//if the button clicked is volume
if(ae.getSource()==volume)
{
//calculate the volume
double v=pi*r*r*h;
//set the textarea to the following
output.setText("Volue of cylinder with radius "+r+" and height "+h+" is "+(int)(v*100)/100.0);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.