255 Lab4 Master
255 Lab4 Master
Goals
In this Lab you will:
1. Learn how to use NetBeans to design a simple GUI without having to write the code for it
yourself.
2. Implement a simple 4-function calculator Desktop app.
Resources
You will want to refer to each and all of the following to complete this Lab:
1. Lab Overview (this document).
2. Calculator.java, the Starter Code for this Lab (attached).
Background
So far, all of the programs we’ve made in lab have used archaic, text-only interfaces for interacting
with the user. That changes in this Lab; when you’re done, you’ll have a program you can run
that will pop up a window with buttons on it and interact with mouse clicks (or, if run on a tablet,
finger taps).
Specifically, we will be implementing a Single-Step Calculator, similar to the built-in utility on
Windows and MacOS. It will look like this when you’re done:
1
CIT255 Overview Lab4 - The Calculator
This section will explore how such a calculator works in the abstract; then in What To Do, And
How we’ll get into actually building it.
Single-Step Calculators
2 + 3 ∗ 5 = 25 (1)
Note that reading this section is only necessary if you are interested in how the calculator works.
Otherwise, you can skip ahead to What To Do, And How.
Any combination of button presses on our calculator will affect just these 5 variables:
1. result, which starts as 0.
2. operation, which starts as ‘=’.
3. error, which starts as false.
4. displayLen, which starts as 0.
5. disp, which starts as "".
2
CIT255 Overview Lab4 - The Calculator
Note that reading this section is only necessary if you are interested in how the calculator works.
Otherwise, you can skip ahead to What To Do, And How.
Whenever displayLen is 0, the calculator should display the value of result, to the most sig-
nificant 10 digits (or 9, if “.” is one of the characters displayed), truncated (so you can use
String.substring() instead of having to worry about rounding properly).
Whenever displayLen is not 0, the display should show the value of disp.
Note that, because there may be a leading negative sign, up to 11 actual characters may be required
to display either result or disp, and that displayLen is not always exactly the same thing as
disp.length().
There are 11 buttons for entering a number: “0” through “9” and “.”. Generally, clicking any of
these should increment displayLen and append the appropriate char to disp, unless displayLen
>= 10, in which case the button click should just be ignored. However:
• “.” can not be used if it is already present in disp or displayLen >= 9; subsequent clicks
should just be ignored.
• if and only if disp is “0” and the char for the button press is not “.”, the “0” should be
replaced by the char.
“C” (for “Clear”) sets displayLen to 0 and disp to "". Note that it has no effect if displayLen
was already 0 and disp was already "".
“AC” (for “All Clear”) sets all 5 variables to their default state (see above).
For the rest, let Q be whatever number is displayed - disp if displayLen > 0, result otherwise -
treated as a number (not as a string). Generally you should wait to calculate Q until you need it
for one of the following button presses, as the user may not be done entering digits.
√
The two buttons “ ” and “±” are immediately applied to Q, as square root or negation. Call the
result T. We then update disp to be the String form of T, to maximum precision (i.e. 9 or 10
digits, so the user can’t type anything more), and also update displayLen accordingly.
The buttons “=”, “+”, “-”, “x”, “÷”, all behave the same way. They trigger an evaluation under
the operation implied by operation operating on the variables result and Q: note that operation
is probably NOT the operation represented by the button itself (e.g. if operation is “-” and
the “+” button is pressed, the evaluation would complete the lingering subtraction, not do the
addition). To be explicit, the various evaluation possibilities given operation are:
1. operation == ‘=’ causes result = Q.
2. operation == ‘+’ causes result = result + Q.
3. operation == ‘-’ causes result = result - Q.
4. operation == ‘x’ causes result = result * Q.
3
CIT255 Overview Lab4 - The Calculator
We’re going to be using NetBeans a little bit differently than we have been, so be sure to pay close
attention to the next bunch of screenshots. To start with, we’re going to start a new Project...
...but then immediately deviate from our usual pattern. In particular, do NOT create the Main-Class
4
CIT255 Overview Lab4 - The Calculator
Instead, after creating the project, we’re going to right click the “default” package and create a
new JFrame Form:
5
CIT255 Overview Lab4 - The Calculator
NetBeans has created a special entity, and you and NetBeans are going to take turns adding Java
code to Calculator.java. When you right click the file and say “Edit”, it will put you in the
familiar code editor. But when you right click and say “Open”, you enter a WYSIWIG Gui Form
editor for the class instead:
6
CIT255 Overview Lab4 - The Calculator
The very first thing we want to add is a MenuBar, which you drag in from the section called
“Palette”:
The default MenuBar has File and Edit - click around on “Edit” until it lets you select and change
the text, then rename it to “Help”:
7
CIT255 Overview Lab4 - The Calculator
These menus currently have nothing in them. To change that, from the Palette, drag one MenuItem
under each Menu. The one under File should say Quit, and the one under Help should say About.
You can change the display text either by clicking and editing like you did the Menu headings, or
you can find the Text entry under Properties off to the right and edit it there.
8
CIT255 Overview Lab4 - The Calculator
If you were to run the program now, you’d see this window popup. The MenuItems currently do
nothing when selected.
9
CIT255 Overview Lab4 - The Calculator
Right click anywhere under the menus, and select “Layout” - confirm that BorderLayout is selected:
Next, we drag in a TextField, where we will show numbers in the calculator. When dragging,
make sure to drop just below the Menus, so that it registers with a NORTH layout attribute. If it
doesn’t go where you want it, keep trying to drag it to where it should go until it gets there:
With the TextField selected, we want to change some of the fields using the Properties tab. We
want Editable off; to change the name of TextField in code to display; and we want the default
text for the TextField to be "":
10
CIT255 Overview Lab4 - The Calculator
11
CIT255 Overview Lab4 - The Calculator
We’re not done with display yet. Still selected, we want to change text alignment to “Right” using
horizontalAlignment; to change the font size to be bigger; and to add some margins around the
four sides of the TextField, essentially making it bigger when we start adding buttons later:
12
CIT255 Overview Lab4 - The Calculator
Now we’re ready to add our buttons. First we’re going to add a JPanel, which will let us ap-
ply a GridLayout to our buttons. When dragging and dropping the panel, make sure it lands as
BorderLayout.CENTER on the overall form, or drag it around until it’s where you want it. Some-
times NetBeans gets confused and makes GUI elements children of the wrong thing - you can change
that by dragging over in the bottom left where it says Navigator:
13
CIT255 Overview Lab4 - The Calculator
Change the Layout to GridLayout, and via Properties change it to 4 columns and 5 rows:
14
CIT255 Overview Lab4 - The Calculator
Now we’re going to add a bunch of JButtons. 20 to be exact! If you’re successfully dragging them
into the Panel, and your GridLayout selection is right, they should auto-arrange into a nice 4x5
grid. Otherwise, make sure you aren’t accidentally setting them as children of the underlying Form,
and that your earlier settings are correct. When you’re just starting, the buttons will arrange
themselves in fewer rows and columns than the final result. Depending on NetBeans, your buttons
names may also be different from the screenshots - that’s ok.
15
CIT255 Overview Lab4 - The Calculator
It’s starting to look like a calculator, isn’t it? Now we need to go in and make the buttons say
what we want them to say at runtime. Clicking on any button to select it, you can change its text
under the Properties section:
16
CIT255 Overview Lab4 - The Calculator
17
CIT255 Overview Lab4 - The Calculator
A few of the buttons have weird symbols that aren’t easily typed on a keyboard. If you don’t know
how to type arbitrary unicode sequences, feel free to visit Wikipedia and just copy the character
from the web page. You can paste it in to NetBeans directly1 .
1
The square root sign may or may not copy over correctly from a Google search (search for “square root symbol”
and try to copy/paste the symbol into NetBeans). If it does not work, you may want to try this alternative. Sometimes
we have found that pasting HTML in as text works in NetBeans. The magic formula is <html>radic;</html>.
18
CIT255 Overview Lab4 - The Calculator
There’s a few odds and ends left from earlier. We need to specify the “Preferred Window Size” for
the overall form when the program runs2 :
2
Note that the next few screenshots don’t match the same grid dimensions from earlier. That’s OK, and you can
have different grid dimensions from the handout, as long as you have the same number of buttons.
19
CIT255 Overview Lab4 - The Calculator
We also need to change the variable names for the quit and about buttons, using the “Code” tab:
20
CIT255 Overview Lab4 - The Calculator
We want those menu items to do something when we click them. To do that, go back and select
them, and then look under the Events section. You want to click where it says <none> under
actionPerformed, and select the default text it offers you. Doing so should pop you back into the
editor:
When you’ve done it for both menu items, you should see something that looks like the following.
21
CIT255 Overview Lab4 - The Calculator
It’s up to you to fill quitActionPerformed() and aboutActionPerformed() in with code (see the
next section for hints):
Unfortunately, the next section is a little tedious; NetBeans tries to be helpful and instead gets
in the way. Select the first button, and go to Events. In the triple dot menu to the right of
actionPerformed, we want to Add a new Handler. Call it calculatorButtonPressed. Make sure
this new handler ends up selected for actionPerformed under the drop down menu.
Back in code edit mode, this is the code that should go in that method:
22
CIT255 Overview Lab4 - The Calculator
This is where it gets tedious. For all 19 of the remaining buttons, you need to select the actionPerformed
entry, but then either type in or paste the name calculatorButtonPressed. Each time you do,
NetBeans will switch you to edit mode to go look at it. Calmly switch back (via right click, “Open”)
to GUI editing mode each time.
Hurray! You’re done editing in GUI editing mode, if you want to be. Feel free to poke around
and change other settings if you want.
23
CIT255 Overview Lab4 - The Calculator
We have just a little bit of finishing up to do to the code NetBeans added for us.
First, in regular editor mode, go to the constructor and add these two lines:
Second, from the attachment later on in this handout, copy in the Starter Code, at the very
bottom of your Calculator.java. A note of warning - NetBeans will not let you edit most of the
code it wrote for you, requiring you instead to go back into GUI editing mode to change it. But
once you’ve made some space at the end of the file and pasted in the Starter Code, you should
be able to edit all of that in NetBeans as normal:
24
CIT255 Overview Lab4 - The Calculator
2. You will need to add the ÷ symbol to one of the cases of the switch statement, contained in
the function exec. The ÷ symbol most likely will not copy correctly from the PDF.
3. You will need to re-format the following line of code:
String asStr = String . format ( " %. " + ( MAX_DISPLAY_LEN ) + " f " ,
So that there are no spaces in between each double quotes and the enclosed text. Most likely
copying from the PDF will create additional whitespace which will cause your program to
give an error.
4. Add a single line of code to the actionPerformed handler for the quit button, to make the
application exit immediately.
5. Add a single line of code to the actionPerformed handler for the about button, using
JOptionPane, to announce your name, the year you wrote this, and that this was made by you
(and anything else you might like to say). (Hint: javax.swing.JOptionPane.showMessageDialog).
25
CIT255 Overview Lab4 - The Calculator
26
CIT255 Calculator.java Starter Code Lab4 - The Calculator
Unlike in past Labs, this is not a full Java file to begin with. Instead, you will use NetBeans
to automatically generate much of Calculator.java, then copy and paste the following into the
bottom of it to finish the Lab.
...
return asStr ;
}
27
CIT255 Calculator.java Starter Code Lab4 - The Calculator
{
display . setText ( toDisplayString ( result ) ) ;
}
}
displayLen = 0;
disp = " " ;
}
28
CIT255 Calculator.java Starter Code Lab4 - The Calculator
if ( error )
{
return ;
}
29
CIT255 Calculator.java Starter Code Lab4 - The Calculator
operation = code ;
}
}
// Step 2 - Apply the effect of that button ( see the " Background "
// section in the handout ) .
handlePress ( letter ) ;
...
30