IT 5 Lesson 7 - A Java Calculator Project
IT 5 Lesson 7 - A Java Calculator Project
Click the Finish button, and NetBeans will create the project, but not much else. Have a look at the
Projects area on the left in NetBeans and you should see this (If you can't see the Projects area,
clickWindow> Projects from the NetBeans menu at the top):
1
Normally, there's a .java file under the Source Packages name. But because we unchecked the "Create
main class" box, there's no java class file there.
What we'll do is to add a Form to the project.
When the form is created, it will be created in its own java class file.
To add a form, right click the project name in the Projects window. A menu will appear:
Here, you are being asked for a name for your Class, and a package name.
We've already created the project, and called it MyCalculator.
The package name and class will go into the project. So, for your Class Name type JavaCalculator. In
the blank package text box, type jCalculator. So we're creating a class called JavaCalculator, which is in
the jCalculator package, which is in the MyCalculator project.
Click the Finish button to complete the process.
In the next part, you'll see what happens after you click finish, and explore the various windows of the
NetBeans IDE.
2
The form is blank, at the moment, and has an orange rectangle surrounding it. The orange
rectangle means that the form is the currently selected object. Click away and you'll see a
blue rectangle instead. This means that the form is not selected. Click back onto the form
to select it, and you'll see the orange rectangle again. Note the two buttons at the top,
Source and Design. You're in Design at the moment. Click on Source to see the following
code:
You can expand and contract the plus symbols to reveal and hide code.
Notice, though, that a main method has been created.
When the program starts it's the main method that will be called.
It's creating a new object from our form, and setting its visible property to true. But
NetBeans generates all this code for you. Otherwise, you'd have to do it all yourself!
Have a look at the Projects area on the left again.
You'll see that a package and a class file have been added:
Click back on the Design button at the top. You'll see your blank form again.
To the right, you'll have noticed two areas:
• A Palette with a lot of controls in it, and
• A Properties area.
The Palette should look like this:
3
And the Properties area should look like this:
(If you can't see them, click Window> Palette and Window > Properties from the NetBeans menu.)
A property of an object is a list of the things you can do with it, like set the background color, set the
text, set the font, and lots more. Let's change the title.
Make sure your form is selected. If it is, it will be surrounded with an orange rectangle.
The properties area will say JFrame at the top.
Click inside of the title area and type Calculator:
You only have one, which is in your JavaCalculator class, so just click OK. Your form should then appear:
4
The form has the title you just typed, plus some default icons for minimize, maximize and close.
Click the X to close your program, and return to the Design environment.
In the next part, we'll add a text box to the form.
5
You can hold down your left mouse button on one of the squares and drag to a new width or height.
The dotted lines are position indicators, one for the left position and one for the top position. Notice
that the default name for the text field is jTextField1. Let's change that. With the text field selected,
have a look at the Inspector area in the bottom left: (If you can't see an Inspector area, click Window >
Navigating > Inspector from the NetBeans menu bar.)
As you can see, jTextField1 is selected in the Inspector.
This area shows you what objects you have on your forms. You can also rename an object from here.
To do so, right click on jTextField1. From the menu that appears, select Change Variable Name.
Click OK. When you do, NetBeans will rename your text field:
Now have a look at your code again by clicking the Source button in the main window.
When your code appears, scroll down to the bottom.
You'll see that a new private field variable has been added:
6
So a JTextField variable has been set up with the name txtDisplay.
The "javax.swing" part is a reference to a set of packages that are used for GUI development.
Swing makes it easier for you to create forms and the controls on forms.
Click on the Design button at the top to return to your form.
The text field has some default text in, at the moment.
You can add your own text by changing the text property of the text field.
Make sure your text field is selected on the form. Now locate text in the properties window:
The text field on our calculator will obviously be used for the output of the calculation. But it
won't work without buttons. You'll see how to add those in the next part of this tutorial.
7
So locate the Panel control in the Palette:
Drag one on to your form.
You can't see a Panel, as they'll have the same color as the form. But you can select it:
Drag the sizing handles so that the Panel fills most of the form:
You should then see a button with sizing handles and position lines:
The new variable name is btnOne, and it is a JButton object, which is a Swing control. Note,
too, that a variable has been set up for the panel (we've left this on the default name).
In the next part, you'll learn how to change the properties of Java buttons.
5. Button Properties
In the last part, you saw how to add a button to your Java form.
In this lesson, you'll see how to change its properties.
Go back to Design view and make sure your button is selected.
9
We can change the text on the button.
What we want is a number, one number for each button on the calculator. The text
property is used for button text. So locate this property in the properties window. Delete
the default and type the number 1 instead:
Press the enter key on your keyboard and you should see the text change on your button.
It will also be resized:
You can change the size of the button in the properties window.
Locate Horizontal Size and Vertical Size, under the Layout heading:
Change these values from the default to 50, 30:
You can also change the font and font size in the properties window.
Make sure your button is selected.
Now locate the font property. Click the small button to the right of the font row:
10
When you click the font button, you should see a dialogue box appear.
Change the font size to 14 points, and make it bold:
Your form should now look like this (to see the outline of the panel, just hover your mouse over it):
You now need to add nine more buttons in the same way, for the numbers 2 to 9, and a 0.
Change each variable name to btnTwo, btnThree, btnFour, etc.
Delete the default text, and enter a number instead.
Then change the size of each button to 50, 30.
Finally, change the font property of each button.
When you're finished, your Inspector area should look like this:
11
(Note that the 0 button has the name btnZero.)
If your buttons are in the wrong place, click a button to select it. Hold down your left mouse button.
Keep it held down and drag to a new location in the panel.
To move all the buttons at once, select the panel and drag it to a new location: When you're happy
with your form, it should look something like this (We've resized the text field):
Only three more buttons to add: a plus button, an equals button, and a clear button. We'll add
these to a panel of their own, and move them to the right of the calculator. As you can see, our
calculator doesn't have any room on the right. But you can easily resize a form. Click on just the
form, and not the panel or the text field.
If you do it right, you should see an orange rectangle surrounding the form.
Now move your mouse to the edges of the form.
The mouse pointer should change shape, as in the image below (bottom right):
Hold down your left mouse button when the pointer changes shape.
Now drag to a new size.Add a panel in the space you've just created:
12
Add three buttons to the new panel. Change the variables names to: btnPlus, btnEquals, and btnClear.
For the text for the buttons, type a + symbol for the Plus button, a = symbol for equals button, and the
word "clear" for the clear button.
Change the font to the same as the number buttons, 14 point bold.
The size for the plus and equals button should be the same as the number buttons: 50, 30.
For the Clear button, change it to 70, 30. Your form should then look like this:
You can run your form at this stage, just to see what it looks like:
Looking quite nice, hey! Nothing will happen when you click on the buttons, though.
We'll add some code shortly. First, a word about Events.
13
But the very act of clicking generates an event object. The event object then looks for an object that is
listening out for, say, a mouse click, or a keystroke, or any other event that can happen on a form. A
text field, for example, can be listening out for key strokes. Or a drop down box could be listening out
for which item in the list was clicked.
Different objects (sources) fire different event.
For a button, the event that is fired is theActionListener.
For a text field, it's the KeyEvent.
Think of like this: the event object is responsible for passing messages back and forward between form
objects that have had something happen to them, and objects that are waiting for things to happen. If
all this sounds a bit complicated, then don't worry - it is complicated! But some programming
examples might clear things up.
First, a word about how our calculator will work.
If we want to add 3 + 2, we first need to click the 3 button.
The number 3 will then appear in the text field.
The plus button is clicked next, and this alerts the program to the fact that we want to add things. It
will also clear the text field ready for the next number.
The next number is 2, and we store this value along with the 3.
The equals button is clicked to get the total, and this is where we take the stored numbers (3 and 2)
and add them together. Finally, the answer is stored in the text field.
The first problem is how to get at the numbers on the buttons.
We can do this by returning the text property of the button.
Once we have the text, we can put it into the text box.
But we need an ActionEvent for when the button is clicked.
In Design view in NetBeans, select your number 1 button.
Now have a look at the Inspector window in the bottom left. Locate your btnOne button.
Now right click to see the following menu appear:
Select Events from the menu. From the submenu, click on Action, and then actionPerformed:
14
When you click on actionPerformed, you will create a code stub for btnOne:
private void btnOneActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
The first line is a bit long. But it's just a method with an ActionEvent object between the round
brackets. When the button is clicked, whatever code we write between the curly brackets will get
executed.
15
To do that, you can simply get the text from the text field and combine it with the button text.
Amend the first line of your code to this:
String btnOneText = txtDisplay.getText() + btnOne.getText();
Now we're saying get the text from the text field and combine it with the button text.
Store the result in the variable called btnOneText.
Run your program again, and click your number 1 button a few times.
You should find that the text field will display a series of 1's:
We can add the same code for all the number buttons on the calculator.
Go back to design view. Instead of right-clicking in the Inspector area, another way to add an Action for
a button is to simply double click it. So double click your number 2 button.
A code stub will be created, just like last time.
Add the following code to it:
private void btnTwoActionPerformed( java.awt.event.ActionEventevt ) {
String btnTwoText = txtDisplay.getText() + btnTwo.getText();
txtDisplay.setText( btnTwoText );
}
The only difference with the code is the name of the String variable (now called btnTwoText), and the
fact that we're getting the text from btnTwo.
In between the round brackets of setText, we pass the name of the String variable.
Run your program again.
You should now be able to click the 1 and the 2 buttons and have the text appear in the text field:
Add the same code for all of your calculator buttons.
So double click each button to get the code stub, and add the two lines of code for each button.
You will need to change the name of the String variable. Here's the code for button 3: String
btnThreeText = txtDisplay.getText() + btnThree.getText();
txtDisplay.setText( btnThreeText );
You can copy and paste the code you already have. Then just change the String variable name, the
name of the button after the btn part, and the part between the round brackets of setText.
16
If you see any underlines then you know you've done something wrong. When
you've finished, the code for all the number button should look like this:
Run your calculator and test it out.
You should be able to enter all the numbers from 0 to 9:
In the next part, you'll write the Java code for the Plus button on your calculator.
17
7. Coding for the Plus Button
Now that the number buttons are working on your Java calculator, the next thing to do is to handle the
plus button. The only thing our plus button needs to do is to store whatever number is currently in the
text field. It's just a record of the first number to be added. Later, we'll also record the fact that it was
the plus button that was clicked, rather than the minus, or the divide, or the multiply button.
To store the value, we need to set up a field variable, that's a variable outside of any button code.
This is so that all the buttons can see what has been stored in it.
Add the following variable near the top of the coding window: (You can place it near the bottom, with
the field variables NetBeans has set up for the form objects, but we'll keep our variables separate.)
private double total1 = 0.0;
Here's the code window:
So we're setting up a variable called total1. The type of variable is a double. Its default value is 0.0.
To store the value from the text field, we need to get the text.
But we'll need to convert it from a String to a Double.
You can do so with the parseDouble method of the Double object:
Double.parseDouble(txtDisplay.getText( ) )
In between the round brackets of parseDouble we get the text from the txtDisplay text field.
However, when we store the value from the text field into the total1 variable, we need to retain what
is already in total1.
We can also clear the text field, ready for the second number.
So return to Design view in NetBeans.
Double click your Plus button to generate the code stub.
Now add the following two lines to your plus button:
total1 = total1 + Double.parseDouble(txtDisplay.getText( ) ) ;
txtDisplay.setText("");
In between the round brackets of setText, we have a pair of double quotes, with no space between
them. This is enough to clear the text field.
And that's it for the Plus button, for the moment. We'll come back to it later.
All we're doing, though, is storing a number in the total1 variable, and keeping what is already there.
Once the number is stored, we've cleared the text field.
The user can now enter a second number to be added to the first.
In the next part, we'll add code for the equals’ button on our calculator.
To get the answer to the calculation, we take whatever is currently stored in total1 and add it to
whatever is currently in the text field.
Again, though, we need to parse the string from the text field and turn it into a double.
Go back to Design view and double click your equals button.
In the code stub that is created, add the following line:
total2 = total1 + Double.parseDouble(txtDisplay.getText( ) );
This line gets the text from the text field and converts the string into a double. The
result is then added to total1. The answer is then stored in the total2 variable.
The next thing we need to do is to display the answer to the calculation back into the text field.
However, we now have to convert the double back into a string, as text fields hold text and not
numbers. If you try to store a double value directly into a text field you'll get errors.
To convert a double into text you can use the toString method of the Double object.
Add the following line just below the first one:
txtDisplay.setText(Double.toString( total2) );
The conversion is done between the round brackets of setText.
But you could set up a new variable, if you wanted:
String s1 = Double.toString( total2 );
txtDisplay.setText( s1 );
But the result is the same: convert a double to a string.
The final line for the equals button can clear the total1 variable.
Once the total1 variable is cleared, a new calculation can be entered. Here's the line to add:
total1 = 0;
The three lines for your equals button should now be these:
total2 = total1 + Double.parseDouble( txtDisplay.getText( ) ) ;
txtDisplay.setText( Double.toString(total2) );
total1 = 0;
In the next part, we'll write code for the Clear button. You'll also get to try a few exercises.
Exercise
Set the font property for your text field so that it's 14 point bold.
When you've completed the above exercises, you calculator should look something like ours:
Once you've added the new buttons, rename the default variables to btnSubtract, btnDivide, and
btnMultiply. (Another way to rename the variable is to simply right-click the button. You'll then see a menu
appear. Select "Change Variable Name".)
The technique we'll use to get which operator button was clicked is to store the button text in a field
variable. We can then use a switch statement to examine which character is in the field variable. If
it's the + symbol we can add; if it's the - symbol we'll subtract; if it's the / symbol we'll divide; and if
it's the * symbol we'll multiply.
20
So click the Source button to get back to your code.
Add the following field variable to the top, just below your other two:
private char math_operator;
The top of your code should then look like this:
We can set up a method to get at the character on the button that was clicked.
Add the following method to your code:
You can add the above method anywhere in your code, as long as it's between the curly brackets of the
Class, and not between the curly brackets of any other method.
We've called the method getOperator. It's a void method, so won't return any value - it will just get on
with executing the code.
In between the round brackets of the method header, we have a String variable called btnText.
This is obviously the text from the button that was clicked.
The text from the button is a string. However, switch statements in Java can't handle strings, so we
need to convert the string to a character. We do so with this line:
math_operator = btnText.charAt(0);
The charAt method of strings will get a character from a string.
The character you want goes between the round brackets of charAt.
The math symbol from our buttons is always at character 0 in the string.
This is then stored in the char field variable we've just set up at the top of the code.
Notice the other two lines in the code. They are exactly the same as the lines from the plus button,
doing exactly the same thing - storing the first number in the variable called total1. Each operator
button needs to do this, so it makes sense to have these two lines in our method, rather than in the
operator button code.
So locate your btnPlus code and delete the following two lines from it:
total1 = total1 + Double.parseDouble(txtDisplay.getText( ) );
txtDisplay.setText("");
Replace them with these two lines:
String button_text = btnPlus.getText();
getOperator(button_text);
The first new line gets the text from the plus button and stores it in a string variable.
This is then handed over to our method getOperator.
The same two lines can be added to the other operator button, only changing the name of the button.
Go back to design view and double click your subtract button. For the code stub, add the following:
String button_text = btnMinus.getText();
getOperator(button_text);
(Although we've used the same name for the String variable Java won't get confused, as each button_text is local
to its particular button code.)
21
Double click your divide button and add this:
String button_text = btnDivide.getText();
getOperator(button_text);
And here's the code for the multiply button:
String button_text = btnMultiply.getText();
getOperator(button_text);
Now that we have code for all four operator button, we can adapt the equals button. For the
equals button, we can set up a switch statement to examine what is in the math_operator
variable.
switch ( math_operator ) {
case '+':
break;
case '-':
break;
case '/':
break;
case '*':
break;
}
The switch statement has a case for each of the math operators: +, -, /, and *. We haven't added any
code, yet. But have a look at the code you already have for your equals button: total2 = total1 +
Double.parseDouble( txtDisplay.getText( ) ) ;
txtDisplay.setText( Double.toString(total2) );
total1 = 0;
The last two lines are OK, and don't need to be changed.
The first line, however, can be used in the switch statement.
This line, remember, is the one that adds up.
It can be moved up and used as the code for the + case:
case '+':
total2 = total1 + Double.parseDouble(txtDisplay.getText( ) );
break;
If the minus button was clicked, then we can simply change the plus to a minus in the line above:
case '-':
total2 = total1 + Double.parseDouble(txtDisplay.getText( ) );
break;
The case for the divide is then this:
case '/':
total2 = total1 + Double.parseDouble(txtDisplay.getText( ) );
break;
And the case for the multiply character is this:
case '*':
total2 = total1 + Double.parseDouble(txtDisplay.getText( ) );
break;
22
Here's the entire code for your equals button:
Once you've added the new code to your equals button, run your calculator and try it out.
Try the following, to see if it works:
58. 6 + 37.5 (answer should be 96.1)
78 - 25.5 (answer should be 52.5)
68 / 8 (answer should be 8.5)
56.3 * 6.8 (answer should be 382.84)
And that's it - you now have a simple working calculator that can add, subtract, divide, and multiply:
Now that you've had some practice with form objects, let's create a new program that makes use of
the more common controls you'll find on a form.
Prepared by: Chester Cofino
23