How To Implement The GUI Calculator With JavaFX?

GUI Calculator With JavaFX

As a Computer Science Student, if you want to achieve a Good Score in your Final-Year Project and want to stand apart from other fellow students, then you can try to implement the “GUI Calculator with JavaFX”.

JavaFX is a Highly Advanced Topic in Java, utilizing the latest tools to implement various graphical user interface applications. If you are confident in your Java Skills, then only you can try it out.

In this article, we will give you a walk-through on JavaFX GUI Calculator, from the Assignment Sheet to the Working App. Let’s begin our discussion. 

Summary Or Key Highlights: 

  • JavaFX is a GUI toolkit used to create Modern GUI Desktop Applications with Java.
  • To create the JavaFX GUI Calculator, we have to use TextField, Button, GridPane, etc. components.
  • The Code of the JavaFX GUI Calculator is divided into Six Sections for better understanding.
  • The JavaFX GUI Calculator will do the Simple Arithmetic Operations with GUI Effects.
  • With a Full Output Walkthrough, we will understand the workings of the JavaFX GUI Calculator.

What Is The JavaFX Application?

JavaFX is the modern toolkit in Java that is used for the Graphical User Interfaces. Whenever we develop a desktop application, to insert the GUI, we must use JavaFX.

Earlier, there was a Swing Library that helped in the GUI development. But later, the Swing Library was replaced with JavaFX. So, JavaFX is the latest tool that is more Flexible and Powerful.

JavaFX is a Cross-Platform Application, which means it can be used on any Operating System. There are the Stages and Scenes where we can insert different JavaFX Components like Buttons, Text Fields, etc.

What Are The Requirements Of The JavaFX GUI Calculator Assignment Sheet?

Now, before we start developing the JavaFX GUI Calculator, we have to go through its Assignment Sheet. After understanding the Assignment Sheet, we will know what the requirements are.

In this section, we will discuss the Assignment Sheet requirements of a typical JavaFX GUI Calculator. Let us check the following list to know more about such requirements.

  • We have to create a Windows-based GUI Calculator with JavaFX.
  • There will be a Display Screen to show the Inputs and Outputs.
  • There should be the Digits, Operations, Clear (C), and Equal To (=) Buttons.
  • The Calculator should perform Arithmetic Operations like Add, subtract, multiply, and Divide.
  • The GUI Calculator should work on the Input Validation and Error Handling.

What Are The Different JavaFX Components Used In The GUI Calculator?

Now, after checking the Requirements of the JavaFX GUI Calculator Assignment Sheet, it is time to move ahead. The first step of the Practical Implementation will be to discuss the Required JavaFX Components.

The Required JavaFX Components will work as the blueprint for the upcoming practical implementation. So, let us check the following list, where all the required JavaFX Components are mentioned.

  • TextField: The area for User Input and Output will be made with the help of TextField.
  • Button: The Digit, Operation, Clear (C), and Equals To (=) Functions will be created.
  • GridPane: All the Calculator Buttons will be placed in a 4×4 manner using GridPane.
  • MouseEvent: When the buttons are pressed, the Visual Impact will be shown using MouseEvent.
  • VBox: We will vertically place the TextField and GridPane in the Main Layout.
  • Scene: The Scene Component will hold the entire Main Layout and display it.
  • Stage: The Stage Component will call the Scene and represent the Main GUI Window.

What Are Different Sections In The JavaFX GUI Calculator Code?

Now, after describing the components that we are going to use in the JavaFX GUI Calculator, it is time to discuss the practical implementation. So, it is the central theme for which we are all waiting.

Here, we have divided the complete JavaFX GUI Calculator Code into 6 Sections for your better understanding. So, let us start with the very first section, where we have discussed the Necessary Imported Packages.

Section 1: Necessary Imported Packages 

As JavaFX is one of the Complicated Topics, to develop any code with it, we have to call several packages. That is the reason we have created a separate section for it.

Without importing the packages, we can’t work on JavaFX or any component. Let us check the following code snippet, from which we will come to know about the Necessary Imported Packages.

				
					package abc;

// We Will Import Necessary Packages For JavaFX
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


				
			

Explanation Of The Code Snippet: 

  • At first, the Application Package will be called to develop the JavaFX Application and work on it.
  • Later, the Geometry Package will be called to align JavaFX Components like Text, Layout, etc.
  • Then, the JavaFX Component Scene will be called, and with it the Button, TextField Control Packages will also be called.
  • The MouseEvent Package will be called with the Scene and Input Packages.
  • Later, to create the GridPane and VBox components, the Scene Package will again be used.
  • In the end, the Stage Package will be called, which will be used as the Main Window.

Section 2: JavaFX Application Method 

After discussing the Necessary Imported Packages, in this section, we will know about the Application Method. The Application Method is the main starting point of any JavaFX Code.

Let us check the following code, where the JavaFX Application Method is described for the GUI Calculator.

				
					public class ZapCalculator extends Application // Creation Of Application Class
{

    private TextField tf; // TextField Will Be Used To Display I/O

    // Variables to store the first number and the selected operator
    private double n1 = 0; // Variable To Store First Number
    private String opr = ""; // Variable To Store Operator

    private boolean NewN = false; // A Flag To Start A New Operation


				
			

Explanation Of The Code Snippet: [H4]

  • At first, we will provide the Name of the Application (ZapCalculator.java), which will have Application Traits. 
  • To get the features of the JavaFX Application in the ZapCalculator, we will use the Extend Keyword.
  • Later, a TextField “TF” will be created, which will act as the Main Area of work.
  • Also, we will create Two Private Variables for the First Number and Operators.
  • A Boolean Flag “NewN” will be created, which we will use for any New Operation.

Section 3: JavaFX Start() Method 

The JavaFX Start() Method is the Largest Code Snippet Section for the GUI Calculator. All the JavaFX-related work we will perform in the Start() Method. The Start() Method belongs to the Application Method.

To understand the implementation of the Start() Method, we have to check the following code snippet.

				
					@Override
    public void start(Stage primaryStage) // Start Function Of The JavaFX
    {
        tf = new TextField(); // A TextField Will Be Created
        
        tf.setEditable(false); // The User Can't Edit It Manually
        
        // We Are Aligning The TextField With Design
        tf.setAlignment(Pos.CENTER_RIGHT);
        tf.setStyle("-fx-font-size: 20px; -fx-background-color: #E8F8F5; -fx-border-color: #117A65; -fx-border-width: 2px;");

        GridPane gd = new GridPane(); // We Will Create A GridPane For The Buttons
        gd.setAlignment(Pos.CENTER);  
        
        gd.setHgap(10); // The Horizontal Gap Between Buttons
        gd.setVgap(10); // The Vertical Gap Between Buttons
        gd.setStyle("-fx-padding: 20px; -fx-background-color: #D6DBDF;");

        // The Button Texts Will Be Taken In An Array
        String[] bt = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", "C", "=", "+"
        };

        int rw = 1; // Varaible For Row
        int cl = 0; // Variable For Column

        // We Will Use A Loop To Create And Add Buttons
        for (String txt : bt) 
        {
            Button zap = new Button(txt); // The Button Will be Created 
            
            // The Size And Style Will Be Provided
            zap.setPrefSize(60, 60); 
            zap.setStyle("-fx-font-size: 18px; -fx-background-color: #AED6F1; -fx-text-fill: #154360; -fx-background-radius: 10;");

            // This Is The Normal Styles For Buttons
            final String Normal = "-fx-font-size: 18px; -fx-background-color: #AED6F1; -fx-text-fill: #154360; -fx-background-radius: 10;";
            // This Is The Style When Buttons Are Pressed
            final String Pressed = "-fx-font-size: 18px; -fx-background-color: #5DADE2; -fx-text-fill: white; -fx-background-radius: 10;";

            zap.setOnAction(e -> Click(txt)); // We Will Call The Click Function

            // The Button Color Will Change With Mouse Press
            zap.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> zap.setStyle(Pressed));
            zap.addEventHandler(MouseEvent.MOUSE_RELEASED, e -> zap.setStyle(Normal));

            gd.add(zap, cl, rw); // The Button Will Be Added To The Grid

            // Logic To Move To The Next Column And Row
            cl++;
            if (cl > 3) 
            {
                cl = 0;
                rw++;
            }
        }

        // We Will Create A VBox To Take The TextField And Buttons
        VBox layout = new VBox(15, tf, gd);
        layout.setAlignment(Pos.CENTER);
        layout.setStyle("-fx-padding: 20px; -fx-background-color: #EBF5FB;");

        // The Scene Will Be Created And Called To The Stage
        Scene sc = new Scene(layout, 300, 400);
        primaryStage.setTitle("Calculator");
        primaryStage.setScene(sc);
        
        primaryStage.show(); // The Window Will Display With Show()
    }


				
			

Explanation Of The Code Snippet: 

  • At first, a TextField Object “TF” will be created, which can’t be manually edited.
  • Later, we will align the TextField in the Center Right and provide a Style to it.
  • After that, the GridPane “GD” will be created and will be aligned to the Center.
  • The GD for Buttons will have the 10 Horizontal and Vertical Gaps. Also, we will provide a Style to it.
  • Later, the Array “BT” for the Buttons and Variables for Rows and Columns will be created.
  • A For Loop will be used to create Buttons for Digits, Operations, Close, and Equals. For every button, we will give some styles like Normal Style and Style for Button Pressing.
  • After clicking each button, the Click() Method will be called, and the Button-Pressing Style will be activated.
  • After all of these, the VBox Layout will be created, and we will provide different styles to it.
  • Then, the Scene Object “SC” will be created where we will share the VBox Object “Layout”.
  • In the end, we will call the Stage with the “SC” as the argument.

Section 4: Click() Method For Button Click

The fourth section is denoted for the Click() Method. Whenever we click on any Button in the JavaFX GUI Calculator, this function will be used. This function is also related to the Design of the calculator.

Let us check the following code snippet from where you will know the implementation of the Click() Method.

				
					private void Click(String txt) // Method Will Handle The All Button Clicks
    {
        if ("0123456789".contains(txt)) // If Any Number Digit Is Clicked
        {
            if (NewN) 
            {
                tf.clear(); // The Previous Result Will Be Cleared
                NewN = false;
            }
            tf.appendText(txt); // The Digit Will Come To The Display
        }
        else if (txt.equals("C")) // If The Clear © Button Is Clicked
        {
            tf.clear();
            n1 = 0;
            opr = "";
            NewN = false;
        }
        else if (txt.equals("=")) // If The Equal (=) Button Is Clicked
        {
            Calculate(); // The Calculate() Method Will Be Called
        }
        else // If Any Operator Is Clicked
        {
            if (!tf.getText().isEmpty()) 
            {
                // Calculation Of The Value
                n1 = Double.parseDouble(tf.getText()); 
                opr = txt; 
                NewN = true; 
            }
        }
    }


				
			

Explanation Of The Code Snippet: [H4]

  • At first, a Long If-Else Statement will be created in the program.
  • If the user has pressed any Number Button, then the First IF will work, which will show the Input.
  • If the user has pressed the Clear (C) Button, then the Screen will be cleared.
  • If the user has pressed the Equal To (=), then the Calculate() Function will be called.
  • If the user has pressed any other buttons like Operations, then the Operation Symbol will get stored.

Section 5: Calculate() Method For Arithmetic Calculations 

Section 5 will talk about the Calculate() Method. The Calculate() Method is the only function where no JavaFX Design has been done. This Function will only describe the Calculation Logic.

 Let us check the following code snippet where the Calculate() Method is implemented for Arithmetic Operations.

				
					// Method To Perform Arithmetic Calculation
    private void Calculate() 
    {
        if (opr.isEmpty() || tf.getText().isEmpty()) // If No Operator Is Pressed
        {
            return;
        }

        double n2 = Double.parseDouble(tf.getText()); // Variable For The Second Number
        double res = 0;

        // Switch Case For Different Operators
        switch (opr) 
        {
            case "+": res = n1 + n2; break;
            case "-": res = n1 - n2; break;
            case "*": res = n1 * n2; break;
            case "/":
                if (n2 != 0) // Handling The Zero Division Error
                    res = n1 / n2;
                else 
                {
                    tf.setText("Arithmetic Exception Error"); // Handle divide by zero
                    opr = "";
                    return;
                }
                break;
        }

        // The Result Will Be Displayed
        tf.setText(String.valueOf(res));
        opr = "";
        
        NewN = true; // The Calculator Will Be Ready For The Next Input
    }


				
			

Explanation Of The Code Snippet: 

  • At first, we have to check if any Operation is pressed by the user or not in the first If Statement.
  • If there is No Operation, the Calculate() Function will close itself.
  • If not, then a Variable for the Second Number will be created.
  • Then, a Switch Block will be created, which will do the operation based on the Operation Button.
  • In the end, we will call the “TF” and display the result on the screen.

Section 6: Main Method Of The Java Code 

The last but not least section will be for the Main Method. The Main Method of the GUI Calculator with JavaFX is the smallest section we have discussed till now. This section is also not complicated.

In the following section, we will describe the Code Snippet of the Main Method. So, let us check it.

				
					// Main Method To Launch The JavaFX Application
    public static void main(String[] args) 
    {
        launch(args);
    }
}


				
			

Explanation Of The Code Snippet:

  • We will call the Launch() Function in the Main Method.
  • The Launch() Function belongs to the JavaFX Application Method, which will execute the code.

Understanding The Working Of JavaFX GUI Calculator With Output Walkthrough:

We hope the implementation of the JavaFX GUI Calculator should be clear to you from the above extensive discussion. So now, we can move ahead to the next section.

In this section, we will show the working of the JavaFX GUI Calculator with a detailed Output Walkthrough. So, let us start with the first step of the GUI Calculator Working.

1. Entering The First Number: 

When we execute the code, the Calculator Interface will come in front of us. Then, we have to click on any Number Button. Like, we are pressing the Number 3.

When we press the Number 3, the button will become Blue to indicate, the button is pressed. And the Number will come to the screen.

Entering The First Number

2. Choosing The Operator:

After that, we have to press any one operations on the screen. Here, for demonstration, we are pressing the Add (+) Button. However, the Add will not show on the screen.

Choosing The Operator

3. Entering The Second Number: 

After entering the operation, we have to enter the Second Number. At this time, we will press the 6 Button. The first number (3) will be removed from the screen and replaced with the Value 6.

Entering The Second Number

4. Pressing The Equal To (=) Symbol: 

Now, to get the result of the addition, we have to press the Equal To (=) Symbol. While pressing the button will go Blue due to the Pressing Style Effect.

 Pressing The Equal To (=) Symbol

5. Getting The Final Output: 

As soon as we press the Equal To (=) Symbol, the Addition Result will come in front of us. So, the Calculator is working completely fine.

Getting The Output

 6. Clearing The Calculator:

Now, if we want to do another Operation, we have to just press the Clear (C) Button, and the screen will be cleared.

Clearing The Calculator

Conclusion:

In the end, we can say that, implementation of the “GUI Calculator with JavaFX” is not that complicated. Still if you feel stuck, you can always get help with expert help with your JavaFX project

We will advise you to clear the Basics of JavaFX for GUI Development. If your basis of JavaFX is not clear, then you can’t understand and develop different GUI Applications with JavaFX.

Takeaways: 

  • To develop the JavaFX GUI Calculator, we have to import 9 Different Packages into the code.
  • TextField, Variables for First Number, and Operation should be developed under the Application Method.
  • The Start() Function will have the Styles and Alignment of the JavaFX Components.
  • The Click() Method will be used to handle the Button Click Functionality of the GUI Calculator.
  • The Calculate() Method will only work on the Arithmetic Calculations based on operations.
  • The Main Function will only launch the JavaFX Application.