CS401 - Intermediate Programming Using JAVA (Recitation)

 

Lab 5 - Building a Graphical-User Interface with NetBeans
Part 1


Steps to Follow

1. Creating a new project

  • Select File from the menu bar and select New Project (shortcut Ctrl+Shift+N).
    In the New Project window, select General (Categories) and Java Application (Projects). Click Next.

 

2. Setting up your project

  • Type in the name of your project in Project Name (eg. ImageViewer or MyImageViewer, Calculator)
    Enter an appropriate location for your project in Project Location. You can either accept the default or click on Browse to select an alternate location for your project.
    Uncheck the Create Main Class and Set as Main Project checkboxes. We will create the Main class later. Click Finish to accept the values.

 

3. Creating a package

  • Expand the node labeled Source Packages. Right click on it and select New followed by Java Package... in the cascading menu.

    Type in the name of new package (we suggest using Calculator as we will refer to it below). Click Finish.

Summary:
You have just created a new project, and a Java package within it called Calculator. From this point on, be sure to save your project often.

 

4. Creating a GUI

  • Right click on the package name (Calculator) and select New followed by JFrame Form... in the cascading menu.

 

  • When the New JFrame Form dialog appears, type in Calculator in the Class Name field then click Finish.

 

 

 

5. Selecting the layout manager
A new tab containing Calculator should now appear in the middle of the NetBeans window. The Design view should show an empty rectangle representing the Calculator class which is a subclass of JFrame. Since the class is a form, the editor is set to Design mode (instead of Source mode) which provides a point and click interface for designing a form.

  • Right click on the Calculator (shaded box) in the editor and select Set Layout followed by GridBagLayout in the cascading menu.

 

 

6. Adding a title

  • In the Design window, click on the Calculator
    The Properties window should now show the JFrame properties of Calculator

    Look for the title property in the Properties window.
    Click on the corresponding ... button to launch the customizer dialog.
  • Type in the value 'My Calculator' for the Title property

 

  • Click OK.

 

7. Adding Swing widgets to the Calculator

  • Click on JTextField in the Palette to select it.

 

  • Click on the Calculator in the editor.
    A label widget will now be added to the Calculator. This is labeled jTextField1. You will notice that the Palette does not retain state after the chosen Swing component is added to a container. By design, you have to explicitly select a component each time you want to add it from the Palette. This minimizes the occurrences of accidentally adding a component, or adding wrong components.

  • Click on JButton in the Palette to select it then click on the Calculator in the editor.

  • Finally, add sixteen JButtons to your GUI.

 

8. Using GridBagLayout Customizer
After each button has been added, right click on the Calculator in the editor and select Customize Layout... Leave the JTextField untouched but click and drag each button to the appropriate column in the grid. This shows that GUI-components can be moved anywhere to see what looks best while a programmer designs a GUI. Click the Close button to see what you have accomplished. Press Control+Z to undo the last change if you make an error. Make sure the buttons 1 - 4 are in the second row, buttons 5 - 8 are in the third row, buttons 9 - 12 are in the fourth row, and buttons 13 - 16 are in the last row in increasing numerical order.

 

  • Select jTextField1, click on the + button in the Grid Size group labeled () until the jTextField1 fills the whole top row of the grid (see above).

  • Now return to the Design Window and click on jButton1 in the Properties window, change the text from "jButton1" to "7".

 

  • Repeat this process for each of the other buttons until your calculator looks like

 

  • Select the jTextField1, change the font in the Properties panel to Comic Sans 14.

 

9. Testing the GUI

  • From the Build menu, choose Build Main Project. Click OK.

 

  • From the Run menu, choose Run Main Project. Click OK.

 

  • Hopefully you will see

 

  • This GUI is not functional yet.

 

10. Assigning variable name to the GUI-components
The variable names associated with the components created so far are assigned by NetBeans and are not very memorable (jTextField1, jButton1, jButton2, …, jButton16). You may change these to names more meaningful to you.

  • Look in the Properties panel just below its title bar for three button headings Properties, Events, and Code. Click on Code then click on the jTextField1. Change the variable name from jTextField1 to display. Similarly, change the name of each button to an appropriate name. For example, jButton1 to seven, jButton4 to divide, jButton14 to clear, and jButton15 to equal. Name the remaining buttons in an appropriate way.

 

  • As you make these changes, NetBeans is updating Java code for these GUI components to reflect your choice of variable names.

  • In the Design mode, click on the display (jTextField1). In the Properties window, choose the text attribute and erase the contents so that the display appears to be blank. Build and run this program again.

 

 

11. Viewing generated code
To look at the code generated, look for the buttons Source and Design below the Calculator tab, click on Source button. Scroll down to see the variables associated with the calculator.

 

The blue regions inside this window are places where code has been generated (some is hidden in a collapsible region). Click on the + adjacent to the words "Generated Code" to see the code. Using NetBeans frees you from the drudgery of typing each one of these "boring" lines of code associated with the appearance of the GUI.

 

  • Save all files.

 

12. Adding ActionListeners

  • Click on the seven button. In the Properties panel, click on Events then click on actionPerformed. Add a new handler, name it sevenButtonHandler.

 

  • The code (a stub) has been generated for the sevenButtonHandler. Repeat this for each button, naming the handler with respect to the button (for example, addButtonHandler, nineButtonHandler, …). Save all files and close NetBeans.

 

 

13. Finishing the project in TextPad or Dr. Java

  • Open the java file Calculator.java (it is located in the Calculator\src\Calculator folder). Save it in its own folder, compile it (do you get an error-free compilation? If not, remove the package declaration at the beginning of this file. It should compile now.). All of this code was automatically generated for you compliments of NetBeans. Just think about the time it would have taken to build and test this code from scratch (an unappealing task).

 

Insert the following code in the sevenButtonHandler().

StringBuffer current = new StringBuffer(display.getText());
display.setText("" + current.append("7"));

This section of code should look like

 

Now compile and execute the program. Click on the '7' button three times to see if it
displays 777 in the display portion of the calculator.

 

Repeat this process for each button on the calculator corresponding to the digits 1-9. Compile and execute to see if each digit 1-9 is working properly.

 

The code for the '0' button is,

String current = display.getText();
if(current.equals("0"))
display.setText("0");
else{
StringBuffer tmp = new StringBuffer(current);
display.setText("" + tmp.append("0"));
}

Now design the code for the clear button on your own. Does it work properly?

Before programming the operator buttons, immediately following the

public class Calculator extends …

line, add the following lines

private double operandA;
private double operandB;
private char operator;

Let's now program each of the operator buttons. The code for the '*' button or multiply button is

operandA = Double.parseDouble(display.getText());
operator = '*';
display.setText("");

The code for the '=' button or equal button is,

operandB = Double.parseDouble(display.getText());

switch(operator){
case '*': operandA *= operandB;
display.setText("" + operandA);
break;

case '+':
...
case '/':
...
case '/':
...
default:
...
}

Test a multiplication problem like 2 * 7 * 4 * 12 which equals 672 by clicking the following buttons in sequence: 2 * 7 = * 4 = * 12 =. Does your calculator work?

Using multiply as a model, finish programming the other operations in the switch-statement above. When dividing by zero, display a message in the display textfield.
Thoroughly test your calculator.