October 10, 2024

How to Build a Simple Calculator in Java Using Netbeans – Step by Step with Screenshots

This tutorial would take you through the procedure of building a simple calculator in Java. So I would advice, you print it out and follow the instructions.  If you are completely new to Java and Netbeans you can take these two lessons:

You can print out this page so that you can easily follow along (you can also open it in a different display)
 

What you would need

  • Netbeans IDE
  • A pen and a paper(optional)

Step 1: Create an Application in Netbeans. Name the application CalculatorProgram.
If you don’t know how to create new application. You can get it here: Your First Java Program.

Step 2: Add a JFrame Form to the Application
Right-click on the name of the application in the Projects tab by the left of the window and Choose New > JFrame Form
Enter the name pnlCalculator next to the Class Name and click on Finish. You can see that the form is added as shown below


Step 3: Add two JPanels to the form and then resize and position them as shown. You can get Panels at the right hand side in the palettes tab.

Step 4a: Place a TextField in the Form
See Step 4b to delete the jTextField1.
You need to place a TextField on the form, by clicking on TextField from the Palette and clicking in the upper part of the form. Drag to position it as shown in the figure below.

Step 4b: Modify TextField
Right-click on the TextField and click on Edit Text. Delete the text there.
Right-click again and click on ‘Change Variable Name…’.
Delete what is there and enter txtResult

Step 5: Place and  Buttons on the Form. (Don’t change the name here) You can find buttons on the palette tab. Just add the button, resize them until you have enough buttons on the screen

Step 6: Change the text of the buttons
To change the name of a button, right click on the button and choose “Edit Text”. For button 1, just type 1, for button 2, type 2 and so on exactly as it appears below.
At the end of this step, your form would look like this

Step 7: Change the Variable Names of the buttons.
To do that, right-click on a button and click “Change Variable Name“. Change the names according to the outline below. You need to carefully enter the names correctly, otherwise the program may have issues

1-  btn1
2 – btn2
3 – btn3
4 – btn4
5 – btn5
6 – btn6
7 – btn7
8 – btn8
9 – btn9
0 – btn0
+/-  btnPlusMinus
CE – btnClear
+ –  btnPlus
–     btnMinus
/     btnDivision
*     btnMultiplication
Step 8: Preview your design
Click on the Projects tab, locate the name of the Form. In this case it is pnlCalculator.java. Right-click on it and click on Run File.

You wait for a couple of seconds and if you did everything correctly, the form below would be displayed.

You can then close the preview form.

Step 9: View your source code and locate where you will write your first code. Once in the code view, you can scroll up a little to find the position where you would write your first code.


Step 10: Type the code below in the position you identified in Step 9. (You can also copy and paste it there)

static int value1;
static int value2;
static String operator;

Step 11:  Write the code for Button 1(btn1). Right-click on button 1 > Choose Events > Choose Mouse, Choose MouseClicked.
This takes you to where you would write the code for button 1
 

I have highlighted the position to help you find it(remember you may have to scroll up)
You would see something like:
Private void btn1MouseClicked……
Below the next line that says…//TODO, you can write your code.
 


Step 12: Now Write the code for button 1. This means that we need to write a code to specify what happens when 1 is clicked. To to that:
Write the code below in the position as shown in the figure( you can also copy and paste)
        if(txtResult.getText().isEmpty())
        {
            txtResult.setText(btn1.getText());
            value1 = 1;          
        } else {
            txtResult.setText(txtResult.getText()+ ” ” + btn1.getText());
            value2 = 1;
        }

Your code would now look like the one in the figure below:

Step 13: Test Your Program
You can test your program using the procedure you applied in Step 8. When the form displays, Click on 1 to see what happens. If you did everything right, 1 would appear in the display.
Close the form

Step 14:  Write the code for Button 2(btn2). Right-click on button 2, Choose Events, Choose Mouse, Choose MouseClicked.
This takes you to where you would write the code for button 2

Step 15: Write the code below in the position as shown in the figure( you can also copy and paste)

        if(txtResult.getText().isEmpty())
        {
            txtResult.setText(btn2.getText());
            value1 = 2;          
        } else {
            txtResult.setText(txtResult.getText()+ ” ” + btn2.getText());
            value2 = 2;
        }

If you have written it in the right position, your code would be as shown in the figure below:

Step 16: Do the same for buttons 3, 4, 5, 6, 7, 8, 9 and 0

Step 17: Take some time to look through the codes to make sure you got it right. And also get used to various parts of the code. But don’t modify anything!

Step 18: Test the program again

Step 19: Code for the CE (Clear) button
Right-click on CE button, choose events, choose Mouse, choose MouseClick. This takes you to where you would write the code for this button. Copy and paste the code below in the position

  txtResult.setText(“”);

This is the code that would clear the display when the CE button is clicked. Very simple, right?

Step 20: Code for the +(plus) and -(minus), /(division) and multiplication buttons

For the plus button, write the code below:

        if(!(txtResult.getText().isEmpty())){
        operator = “plus”;
        txtResult.setText(txtResult.getText()+ ” +”);
        }

For the minus write the code below:

        if(!(txtResult.getText().isEmpty())){
        operator = “minus”;
        txtResult.setText(txtResult.getText()+ ” -“);
        }

For the division button, write the code below

        if(!(txtResult.getText().isEmpty())){
        operator = “division”;
        txtResult.setText(txtResult.getText()+ ” /”);
        }

For the multiplication button, write the code below:

        if(!(txtResult.getText().isEmpty())){
        operator = “multiplication”;
        txtResult.setText(txtResult.getText()+ ” *”);
        }

Step 21: Test your program. Run the program, test the 0 – 9 buttons as well as the operations. Also test the clear button
Attempt to enter:
4 + 5 and click (=)
Note that nothing happens when you click the equals button.
Note: you can only work with 1 to 9 at this time
Now let’s write code for the equality sign to perform the calculation.

Step 22: Write code for the equality button
This is the code for the equality button(you already know how to find where to place this code)

         double answer = 0;
         if(operator == “plus”)
             answer = value1 + value2;
         else if(operator==”minus”)
             answer = value1 – value2;
         else if (operator ==”multiplication”)
             answer = value1 * value2;
         else if(operator == “division”)
             answer = value1/value2;
        
         String Result = Double.toString(answer);
         txtResult.setText(Result);

Step 23: Test the program (Congratulations!)
Run the program and try a few calculations. What are your observations. You can leave a comment in the comment box below to let me know what you observe. Are there some questions, leave it in the comment box below.

Get Ready for the Next Steps
In the next tutorials we would tidy up by doing the following:

  • Modify this program to handle any number (not just 0 to 9)
  • Answer your questions
  • Handle errors, in case user enters wrong inputs

I would publish it in a couple of days. Just click follow in the button under my name to get notified when I publish the next step. You can also subscribe to the YouTube channel to watch step by step video


3.8 4 votes
Article Rating
Subscribe
Notify of
guest

19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Toyota Tan Cang
Toyota Tan Cang
5 years ago

You really make it seem so easy with your presentation but I find this topic to
be really something which I think I would never understand.
It seems too complex and very broad for me. I’m looking forward for
your next post, I’ll try to get the hang of it!

how to repair vans shoes
how to repair vans shoes
5 years ago

What’s Taking place i am new to this, I stumbled upon this I have found It absolutely helpful
and it has helped me out loads. I hope to
contribute & assist other users like its aided me. Good job.

99Lynne
99Lynne
4 years ago

I can see that your blog probably doesn’t have much visits.
Your articles are interesting, you only need more new visitors.
I know a method that can cause a viral effect on your site.
Search in google: Jemensso’s tricks

TwiceHashira
TwiceHashira
4 years ago

what’s the code for Plus Minus Button?

bursa mantolama
bursa mantolama
4 years ago

I’m extremely impressed with youг writing skills
ɑs well ɑs with the layout on yoսr weblog.Ιs this ɑ paid theme
or didd yⲟu modify іt yourself? Anyԝay keeρ up tһe excellent quality writing, іt’s
rare to ѕee a nce blpg liҝe this one nowadays.

jayakumar
jayakumar
4 years ago

I get error in getText() method, how to solve it?

kindsonthegenius
Admin
4 years ago
Reply to  jayakumar

Have you solved it now?

Emmanuel
Emmanuel
4 years ago

Hey there,
I firstly wanna congratulate you for your impressive work and for the sharing of knowledge.

The JAVA (HOW TO BUILD A CALCULATOR) help me a lot for an assignment.

I’m would like to ask for assistance to complete my assignment: “If the user enters a wrong operator, the program must display the message, “You have entered a wrong operator.”
How will I add the code?

Best regards,

maikel Ashmalla
maikel Ashmalla
4 years ago
Reply to  Emmanuel

Hey Please I want part 2 of this program
I can’t find it and I have to complete this program before 6/15/2020

Divine Grace
Divine Grace
4 years ago

It’s nice

maikel Ashmalla
maikel Ashmalla
4 years ago

Please if u still here help me find part 2

Sandro
Sandro
4 years ago

My operator variable isnt being recognized in the equal button section (step 22)
how do i fix it?

trackback

[…] Part 1: How to Build a Simple Calculator in Java Using Netbeans – Step by Step with Screenshot… […]

Abdulkadir
Abdulkadir
3 years ago

Hey, I’m very interested in your post, but unfortunately I found some error when followed your code my be it’s me ok is there any header file will be included that you didn’t include here
Please I need your assistance

Abdulkadir
Abdulkadir
3 years ago

Here are the error it shows me

emmy
emmy
3 years ago

hello, my calculator doesn’t give the right answer….plz help me

Awalu Levison
Awalu Levison
2 years ago

This is to confirm that it is really working and helpful thing but I have errors in my projects says: jbutton6 and jbutton9 are not recognized. May some one help me to fix this? Any assistance rendered will be greatly appreciated.

paul
paul
1 year ago

yoo i just like to ask wky the plus minues divide multiply +/- clear

i already tried it many times

@@@
@@@
1 year ago

Thank You!!!