Write a Java program using Applet to implement a simple arithmetic calculator.
Program : (Write a java program using Applet to implement a simple arithmetic calculator)
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class ArithmeticCalculatorFX extends Application {
private TextField display;
private double num1, num2, result;
private String operator;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Arithmetic Calculator");
// Create a GridPane layout for buttons
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10, 10, 10, 10));
// Create and set properties for the display TextField
display = new TextField();
display.setEditable(false);
display.setStyle("-fx-font-size: 18");
grid.add(display, 0, 0, 4, 1);
// Create buttons for digits and operators
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
int row = 1, col = 0;
for (String label : buttonLabels) {
Button button = new Button(label);
button.setMinSize(50, 50);
button.setOnAction(e -> handleButtonClick(label));
grid.add(button, col, row);
col++;
if (col > 3) {
col = 0;
row++;
}
}
Scene scene = new Scene(grid, 250, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
private void handleButtonClick(String label) {
switch (label) {
case "=":
calculate();
break;
default:
if (Character.isDigit(label.charAt(0)) || label.equals(".")) {
displayText(label);
} else {
setOperator(label);
}
break;
}
}
private void displayText(String text) {
String currentText = display.getText();
display.setText(currentText + text);
}
private void setOperator(String op) {
if (!display.getText().isEmpty()) {
num1 = Double.parseDouble(display.getText());
operator = op;
display.setText("");
}
}
private void calculate() {
if (!display.getText().isEmpty() && operator != null) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
display.setText("Error");
return;
}
break;
}
display.setText(Double.toString(result));
operator = null;
}
}
}
start
method sets up a JavaFX window with a GridPane
layout for the buttons. Each button's click is handled by the handleButtonClick
method, and the calculator logic is similar to the previous example. The main
method launches the JavaFX application.
Comments
Post a Comment