Java Calculator
Java Calculator
Java Calculator
Step 1: – Create a blank Java project and name it JavaCalculator. Uncheck the Main
class option from the project tab.
Step 2: – To add a Jframe, right click the project name in the Project window.
Step 3: – To the right of the Jframe, there is a Palette with a set of controls on it. Click
the Text Field and apply it on the blank Field form. Now click Properties, then change
the text field to blank. Click on the Code and change the Variable Name to txtDisplay.
Step 4: – Select the Button and drag it to the Jframe form. Change the text and
the Variable Name as we did for the text field.
Step5: – Change the Variable Name to btnOne as we did for the text Field. Enter the
value 1 for the text by selecting the properties. Do the same for all the buttons by
changing the text and the Variable Name.
The Final Jframe structure will be formed.
Step6: – Double click on any of the button. This will take the user to source section
where the major coding of the program is done. The image below depicts
the Source section.
The firstnum term is to accept the first number entered, whereas the secondnum is to
accept the second number stored. The variable result is used to store the output value.
Writing Code for the Number Button on Java
Calculator
To get text from a form object, you can use the getText method of the object (if it has
one). So to get the text from btnOne we could use this code:
Similarly, do this for all the other logics to be performed. For each logic, the operation to
be performed is clearly stated.
The Equal action button performs according to the required logic. For this, we make use
of the if statements. If the user prefers addition, the firstnum and the secondnum will be
added and the answer will be stored in the result.
The Clear button is used to remove the previously used values from the text Display.
For this the secondnum will be set to 0 and the textField must be set to blank.
Now, Save the file and click the Run button as shown below.
Enter the first number, and second number followed by the logic to be applied. Now
click the Equal action button. The result will be displayed on the text Field.
First number is entered.
Now click the Equal sign button, which gives you the result.
The addition operation has been performed successfully. The rest of the arithmetic
operations can be performed in a similar manner.