In: Computer Science
In a JavaFX application there is a TextField control(tfRadius) for taking input of a circle’s radius. A respective square whose diagonal is the circle's diameter can then be created. There are three other controls in this application: a button(btCalculate), two textareas(trCircleArea, trSquareArea). When the button is clicked, the circle's area is calculated and displayed on trCircleArea, furthermore, the square's area is also calculated and displayed on trSquareArea.
Please write the portions of codes which calculates the circle’s area and the square's area when the button(btCalculate) is clicked and both of the calculated areas are displayed on their respective textarea controls(trCircleArea, trSquareArea). Assuming the codes for layout setup are completed and you are only required to complete the calculation part and handling of button click event.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//adding action listener to the button using a lambda expression
btCalculate.setOnAction(e -> {
//parsing circle's radius from tfRadius text field
double radius = Double.parseDouble(tfRadius.getText());
//finding circle's area
double circ_area = Math.PI * radius * radius;
//displaying it in trCircleArea
trCircleArea.setText(Double.toString(circ_area));
//finding square's diagonal (diameter of circle)
double sq_diagonal = radius * 2;
//finding square's area using diagonal, which is half of d^2
//you can check online to know how you get this formula.
double sq_area = sq_diagonal * sq_diagonal * 0.5;
//displaying square's area in trSquareArea
trSquareArea.setText(Double.toString(sq_area));
});
/*NOTE ON FINDING AREA OF SQUARE USING DIAGONAL*/
A diagonal cuts the square into two right triangles, so
diagonal square = sum of squares of other two sides (Pythagoras theorem)
Square has same width and height, so the formula becomes
diagonal square = 2 * (square of side)
here, square of side is the formula to find the area of square, hence
diagonal square = 2 * area
and finally
area = (diagonal square)/2 or (diagonal square)*0.5