22
How to use NetBeans for developing GUI applications The NetBeans IDE provides many excellent features that professional Java programmers have come to rely on, including an excellent tool for building graphical user interfaces (GUIs). This GUI builder is known as the Matisse GUI builder, and it is widely considered to be the leading tool for building GUIs using Swing components. This tutorial presents all the skills you need for using the NetBeans GUI builder to develop the GUI application presented in chapter 15 of Murach’s Java SE 6. Once you learn those skills, you should be able to apply them as you develop the applications presented in chapters 16 through 17 of our book. Please note, however, that this tutorial assumes that you have already read our basic NetBeans tutorial, “How to use NetBeans with Murach’s Java SE 6,” as well as chapter 15 of our Java book. How to develop a form ........................................................... 2 How to create a project for a GUI application ............................................... 2 How to add a form to a project ....................................................................... 2 How to add controls to the form ..................................................................... 4 How to set properties ...................................................................................... 6 Common properties for forms and controls ................................................... 8 How to add code to a form .................................................. 10 How to set the variable name for a control ................................................... 10 How to create an event handler for a control ................................................ 12 How to rename or delete an event handler ................................................... 14 How to enter the code for a form .................................................................. 16 How to run and debug a form .............................................. 18 How to run a form ........................................................................................ 18 How to debug a form .................................................................................... 18 Perspective ............................................................................ 20 MIKE MURACH & ASSOCIATES, INC. 1-800-221-5528 • (559) 440-9071 • Fax: (559) 440-0963 [email protected] www .m ur ac h.com Copyright © 2007 Mike Murach & Associates. All rights reserved.

Jse6 Netbeans Gui Tutorial

Embed Size (px)

Citation preview

Page 1: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 1

How to use NetBeans fordeveloping GUI applicationsThe NetBeans IDE provides many excellent features that professional Javaprogrammers have come to rely on, including an excellent tool for buildinggraphical user interfaces (GUIs). This GUI builder is known as the MatisseGUI builder, and it is widely considered to be the leading tool for buildingGUIs using Swing components.

This tutorial presents all the skills you need for using the NetBeans GUIbuilder to develop the GUI application presented in chapter 15 of Murach’sJava SE 6. Once you learn those skills, you should be able to apply them asyou develop the applications presented in chapters 16 through 17 of ourbook. Please note, however, that this tutorial assumes that you have alreadyread our basic NetBeans tutorial, “How to use NetBeans with Murach’s JavaSE 6,” as well as chapter 15 of our Java book.

How to develop a form ........................................................... 2How to create a project for a GUI application ............................................... 2How to add a form to a project ....................................................................... 2How to add controls to the form ..................................................................... 4How to set properties ...................................................................................... 6Common properties for forms and controls ................................................... 8

How to add code to a form .................................................. 10How to set the variable name for a control ................................................... 10How to create an event handler for a control ................................................ 12How to rename or delete an event handler ................................................... 14How to enter the code for a form .................................................................. 16

How to run and debug a form.............................................. 18How to run a form ........................................................................................ 18How to debug a form .................................................................................... 18

Perspective ............................................................................ 20

MIKE MURACH & ASSOCIATES, INC.1-800-221-5528 • (559) 440-9071 • Fax: (559) [email protected] • www.murach.comCopyright © 2007 Mike Murach & Associates. All rights reserved.

Page 2: Jse6 Netbeans Gui Tutorial

2 How to use NetBeans for developing GUI applications

How to develop a form

If you read our basic tutorial for working with NetBeans, you already knowhow to create a project and add packages to a project. Once you do that, you canuse NetBeans to develop a form. A form is the window that holds the controlsthat make up the graphical user interface. In this topic, you’ll learn how to useNetBeans to develop the form for the Future Value application that’s presentedin chapter 15 of Murach’s Java SE 6.

How to create a project for a GUI application

When you create a project for a GUI application, you should deselect theCreate Main Class check box so a main class won’t be automatically generated.Instead, the class for the first form of your application is going to be used as themain class.

How to add a form to a project

Before you add a form to a project, you should create the package whereyou want to store the form. In this figure, for example, I created a packagenamed murach.ui (ui stands for user interface) to store the form. Then, I right-clicked on this package and selected the New�JFrame Form command todisplay the dialog box shown in figure 1. Since this automatically enters themurach.ui as package for the form, I only needed to enter the name for the form.In this figure, I entered FutureValueFrame.

For most GUI applications, you base the form on the JFrame class. Forexample, the forms presented in chapters 15 through 17 of Murach’s Java SE 6are all based on the JFrame class. However, it’s also possible to base a form onother classes. If, for example, if you want to create an applet, you can base theform on the JApplet class as described in chapter 18 of our book. To do that,you can right-click on the package, and select the New�JApplet Form com-mand.

The JFrame class is a Swing component that’s available from thejavax.swing package. As a result, when you base a form on the JFrame class,you are using Swing to develop your GUI. Since the NetBeans GUI builder isdesigned to work with Swing components, you may have to use a different GUIbuilder if you need to work with a GUI component library like SWT.

Page 3: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 3

The New JFrame Form dialog box

Description• For a GUI application, you need to start a new project without a main class. Then, you

can use the first form of the application as the main class.

• To add a form to a project, right-click on the package you want to add the form to andselect the New�JFrame Form command. Then, enter a name for the class.

Figure 1 How to add a form to a project

Page 4: Jse6 Netbeans Gui Tutorial

4 How to use NetBeans for developing GUI applications

How to add controls to the form

When you add a form to a project, NetBeans displays the form in Designview. When a form is displayed in this view, the Design button is selected andthe Palette window is displayed on the right side of the NetBeans window.When you’re working with forms, you can usually open a form in Design viewby double-clicking on its .java file in the Projects window.

Figure 2 shows how you can use the Palette window to add controls to theform. The easiest way to do that is to click on the control in the Palette windowand then click on the form where you want to add the control. In this figure, forexample, the JButton control is selected in the Palette window and the user justclicked the mouse pointer to add the second button to the form.

Once you add a control to a form, you can resize the control by clicking onthe control to display its sizing handles and then dragging one of the handles.Similarly, you can move a control by dragging the control to a new location onthe form. As you work with the controls on the form, you’ll find that alignmentguides will appear and attempt to help you align controls with the other controlson the form. In this figure, for example, a horizontal guide is attempting to alignthe second button with the first button. In addition, a vertical guide is attemptingto align the right side of the second button with the right side of the four textboxes.

Most of the time, these guides are helpful and make it easier to developforms that are visually pleasing. Other times, these guides can make it difficultto place controls where you want them to be placed. However, with a littleexperimentation, you should figure out how best to work with these guides.

If you want to change the size of the form, you can drag its edges. In thisfigure, for example, the form is too tall and too wide for the controls. As aresult, it makes sense to drag the bottom and right sides of the form to make itsmaller.

If you need to work with several controls at the same time, you can selectmultiple controls by holding down the Ctrl key as you click on the controls. Or,you can click on a blank spot in the form and drag an outline around the con-trols you want to select. Then, you can work with the selected controls. Forexample, you can align a group of selected controls by clicking one of thealignment buttons in the toolbar for the form’s window.

Page 5: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 5

A form after some controls have been added to it

Description• To open a form, use the Projects window to navigate to the form. Then, double-click on

the .java file for the form.

• In Design view, NetBeans shows a graphical representation of the form. In Source view,NetBeans shows the source code for the form.

• To switch between Design view and Source view, click on the Design and Source buttonsthat are above the form window.

• To add a control to a form, select the control in the Palette window and click on the form.

• If the Palette window isn’t displayed, you can display it by selecting the Palette com-mand from the Window menu.

• To select a control, click on it. To move a control, drag it. To size a control, click on itand drag one of its handles. To change the size of the form, drag its edges.

• To select more than one control, hold down the Ctrl key as you click on the controls. Or,click on a blank spot in the form and drag an outline around the controls.

• To move a group of controls, drag one of them. To align a group of controls, click one ofthe alignment buttons that are to the right of the Source and Design buttons.

Figure 2 How to add controls to a form

Page 6: Jse6 Netbeans Gui Tutorial

6 How to use NetBeans for developing GUI applications

How to set properties

After you have placed controls on a form, you need to set each control’sproperties. These are the values that determine how the controls will look andwork when the form is displayed. In addition, you need to set some of theproperties for the form itself.

The text property for a control determines what is displayed in or on thecontrol. In figure 3, for example, the text properties of the two buttons havebeen changed from their default values to “Calculate” and “Exit.”

The easiest way to set the text property for a control is to double-click on itin Design view. Then, you can edit the text property right on the control. Sinceyou need to set the text property for most controls, you can use this technique toset the text property for all of the controls before you begin using the Propertieswindow to set any other properties.

To set the other properties of a form or control, you can work with theProperties window as shown in this figure. To display the properties for aspecific control, display the form in Design view and select the control byclicking it. To display the properties for the form, click any blank area of theform.

In the Properties window, you can select a property by clicking it. Whenyou do, a brief description of that property is given at the bottom of the Proper-ties window. Then, to change a property setting, you can sometimes edit theentry to the right of the property name by typing a new value or by using acombo box or check box control to alter the property. Other times, you need toclick on the ellipsis (…) button that’s displayed to the right of the property todisplay a dialog box that can be used to edit the property.

As you work with properties, you’ll find that most are set the way you wantthem by default. In addition, some properties are set interactively as you sizeand position the form and its controls in Design view. As a result, you usuallyneed to change just a few properties for each control.

When you change a property from the default value, the property is dis-played in bold in the Properties window. As a result, you can easily identify allproperties that you’ve changed. In this figure, for example, the mnemonicproperty and the text property for the Exit button have been changed from theirdefaults and are displayed in bold.

Page 7: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 7

A form after the properties have been set

Description• To change the text that’s displayed on a control, double-click on the control and enter or

edit the text for the control. Or, right-click on the control and select Edit Text.

• To set a property, select a control and use the Properties window to change the property.

• To sort the properties for a control by category or name, right-click in the Propertieswindow and select the appropriate command.

• To search for a specific property when the focus is in the Properties window, type thestarting letter or letters of the property. This starts the Quick Search feature.

• To set a property for more than one control at the same time, select the controls and usethe Properties window to change the property.

• The properties that have been changed from their default values are displayed in bold.

• A description of the currently selected property is normally displayed at the bottom ofthe properties window. If this description isn’t shown, right-click in the Propertieswindow and select Show Description area.

Figure 3 How to set properties

Page 8: Jse6 Netbeans Gui Tutorial

8 How to use NetBeans for developing GUI applications

Common properties for forms and controls

Figure 4 shows some common properties for forms and controls. Note thatsome of these properties only apply to certain types of controls. That’s becausedifferent types of controls have different properties. For example, the mnemonicproperty is available for buttons, but not for labels or text boxes.

For most controls, you use the text property to specify the text that’s dis-played on the control. However, this property works a little differently for eachtype of control. For a label, this property sets the text that’s displayed by thelabel. For a text box, this property sets the text that’s displayed within the textbox. For a button, this property sets the text that’s displayed on the button. Andso on.

For simple applications, you only need to set a few properties for eachcontrol. To learn more about the properties that are available for a control, selectthe control and use the Properties window to review its properties.

Page 9: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 9

Common properties for formsProperty Description

title Sets the text that’s displayed in the title bar for the frame.

defaultCloseOperation Sets the action that’s performed when the user clicks on the Close button in theupper right corner of the frame. The default value, EXIT_ON_CLOSE, causes theapplication to exit.

resizable Determines whether the user can resize the frame by dragging its edges.

Common properties for controlsProperty Description

text Sets the text that’s displayed on the control.

editable Typically used for text boxes and other controls that contain text, this propertydetermines whether the user can edit the text that’s stored in the control.

enabled This property determines whether a control is enabled or disabled.

focusable Determines whether the control accepts the focus when the user presses the Tabkey to move the focus through the controls on the form.

horizontalAlignment This property determines how the text on a button or in a text box is aligned: left,right, center, trailing, or leading.

mnemonic Typically used for buttons, this property specifies an access character that allowsthe user to quickly access the control by holding down the Alt key and pressingthe specified character.

preferredSize The width and height in pixels for the control.

Description• To learn about the properties that are available for a control, select the control, use the

Properties window to scroll through its properties, and read the descriptions for eachproperty.

Figure 4 Common properties for forms and controls

Page 10: Jse6 Netbeans Gui Tutorial

10 How to use NetBeans for developing GUI applications

How to add code to a form

In the last few figures, you learned how to add controls to a form and howto set their properties. As a result, if you run the form, it will look the wayyou’ve designed it. However, the form won’t work correctly when you interactwith it until you add the required Java code to the form.

How to set the variable name for a control

When you add a control to a form, NetBeans creates a generic variablename for each of the controls that you add to the form. For example, it usesJTextField1 for the first JTextField control added to the form, JTextField2 forthe second JTextField control added to the form, and so on. Before you writecode that uses any of the controls on a form, though, you should change thesegeneric names to meaningful names that are easier to remember and use.

As figure 5 shows, the easiest way to set the variable name for a control isto right-click on it in Design View, select the Change Variable Name command,and edit the default name. You may want to do this for all of the controls rightafter you set the text property for all of the controls.

Another way to set the variable name for a control is to select the control inDesign view, click on the Code button in the Properties window to access theproperties that affect code generation, and edit the default value for the VariableName property. In this figure, for example, I changed the default value ofJButton2 to exitButton. Once you set the variable names for the controls thatyou’re going to refer to in your code, you’re ready to start writing the code thatwill make your form work the way you want it to.

Page 11: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 11

A form after the variable names have been set for the controls

Typical variable names for controlspaymentTextFieldcalculateButtonmessageLabel

Description• When you add controls to a form, default variable names are given to the controls. If

you’re going to refer to these controls in your Java code, though, you should changethese names so they’re easier to remember and use.

• To change the name of the variable that’s used for a control, right-click on the controland select Change Variable Name. Or, click on the control, click on the Code button inthe Properties window, and change the Variable Name property.

Figure 5 How to set the variable name for a control

Page 12: Jse6 Netbeans Gui Tutorial

12 How to use NetBeans for developing GUI applications

How to create an event handler for a control

An event handler is a special type of method that responds to an event that’striggered when a user interacts with a form. For example, the most commontype of event handler is a method that’s executed when a user clicks on a button.For an event handler to work, it must be connected, or wired, to the event. Thisis known as the event wiring, and it’s generated automatically when you useNetBeans to generate an event handler as described in figure 6.

The most common event that you’ll write code for is the actionPerformedevent. This event is a high-level event that’s raised when a user clicks the buttonwith the mouse or when a user activates the button using keystrokes. However,there are dozens of other events for each control, including low-level events likethe focusGained and focusLost events that occur when the focus is moved to orfrom a control. As you will see, you can use the same general techniques towork with all types of events.

To create an event handler for a control, you begin by displaying the form inDesign view. Then, you can right-click on the control, select Events, and findthe event you want in the submenus. Or, you can click on the control, click onthe Events button in the Properties window, click to the right of the event thatyou want to handle, and press the Enter key. Either way, NetBeans generates adefault name for the method that will handle the event, generates the code forthe event handler and its wiring, and switches to Source view. In this figure, forexample, NetBeans has generated the name exitButtonActionPerformed for theevent handler that will handle the actionPerformed event of the Exit button. Atthis point, you just need to enter the body of the code for that event handler.

If you don’t want to use the generated name for an event handler, you canchange it in the Properties window before you press the Enter key. If, forexample, you want to create an event handler named textBoxFocusGained forthe focusGained event of a text box, you can enter “textBoxFocusGained” to theright of the focusGained event and press the Enter key. Later, if you want towire another text box to the event handler named textBoxFocusGained, you canuse the Properties window to enter “textBoxFocusGained” to the right of thefocusGained event for that text box. That way, the same event handler will beused for two different events.

Below the screen in this figure, you can see the code for the event handlerthat’s generated for the Exit button on the Future Value form. Here, the name ofthe method is the name of the control (exitButton) followed by the name of theevent (ActionPerformed). This shows that it’s important to set the variable namefor the control before you start an event handler for a control. That way, thevariable name will be reflected in the method name of the event handler.

This figure also shows the wiring for the event handler that’s generated forthe Exit button. This wiring is stored in a generated region of code, and youcan’t edit it manually. In addition, you can’t manually rename or delete themethod declaration for an event handler. Instead, if you need to rename ordelete an event handler, you must use the Handlers dialog box shown in the nextfigure.

Page 13: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 13

The actionPerformed event for the Exit button

The code that’s generated for the actionPerformed event of the Exit buttonprivate void exitButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:}

The generated code that wires the event handler to the eventexitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); }});

Description• To create an event handler with a generated name, right-click on the control, select Events,

and select the appropriate event in the submenus. Or, select the control, click the Eventsbutton in the Properties window, click in the text box for the event that you want to handle,and press the Enter key.

• To create an event handler with a custom name, select the control, click the Events buttonin the Properties window, click in the text box for the event that you want to handle, enter acustom name for the event handler, and press the Enter key.

• To wire an event to an existing event handler, enter the name of the existing event handlerbefore you press the Enter key.

• When you create an event handler, NetBeans will generate all of the required code for theevent handler and switch from Design view to Source view so you can complete the code.

Figure 6 How to create an event handler for a control

Page 14: Jse6 Netbeans Gui Tutorial

14 How to use NetBeans for developing GUI applications

How to rename or delete an event handler

When you generate event handlers, there will be times when you will wantto delete the event handler. Sometimes, for example, you will accidentallygenerate an event handler. Then, to delete the handler, you need to display theHandlers dialog box as shown in figure 7, select the event handler, click on theRemove button, and click on the OK button. When you do, the event handlerand its wiring will be deleted from the source code for the form.

There will also be times when you will want to rename an event handler. If,for example, you want to use one event handler to handle multiple events, youmay want to rename it so it uses a name that’s appropriate for all of thoseevents. For instance, the application for chapter 17 of our Java book wires thefocusGained event of three text boxes to the same event handler. But if yougenerate an event handler for the first text box in this application, the defaultname will be paymentTextFieldFocusGained. As a result, you may want torename this event handler to something that reflects the purpose of the eventhandler more accurately.

To rename an event handler, you again display the Handlers dialog box asshown in this figure. Then, you can select the event, click the Rename button,enter a new name for the event handler, and click the OK button. When you do,the event handler and its wiring will be renamed in the source code for the form.

Later, when you generate the event handler for other text boxes, you canwire them to the same event handler that’s used by the first text box as describedin figure 6. To do that, you select the control, click on the Events button in theProperties window, click to the right of the focusGained event, enter the nameof the first event handler, and press Enter. When you do, the focusGained eventof the next control will be wired to the same event handler as the first control.

Page 15: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 15

The Handlers dialog box

Description• Since an event handler includes wiring code that’s automatically generated and stored in

a different location than the event handler code, you should always use the Handlersdialog box if you need to rename or remove an event handler. That way, both the eventhandler and its wiring are updated or removed in a single operation.

• To rename or remove an event handler, select the control, click on the Events button inthe Properties window, and click on the ellipsis button to the right of the event that youwant to work with. Then, use the Handlers dialog box to remove or rename the eventhandler.

Figure 7 How to remove or rename an event handler

Page 16: Jse6 Netbeans Gui Tutorial

16 How to use NetBeans for developing GUI applications

How to enter the code for a form

Figure 8 shows how to enter the code for a form. To start, you should enterany import statements that you need for classes that are going to be used by theform. For instance, after the package statement in this figure, you can see that Icoded an import statement for the NumberFormat class that’s available from thejava.text package of the Java SE API, and I coded an import statement for theFinancialCalculations class that’s available from the murach.business package.After you code these statements, you can refer to these classes in your eventhandlers without qualifying them with their package names.

Next, you can enter the code for the event handlers that you’ve generatedfor the form. In this figure, for example, I have entered the code for the eventhandlers for the actionPerformed event of the Exit and Calculate buttons. As Ientered the code, I used the variable names that I entered to refer to the text boxcontrols. For example, I used the paymentTextField variable name to refer to theentry in the Monthly Payment text box.

Although the code in this figure doesn’t use any helper methods, you canadd helper methods to a form, just as you would add methods to any other class.For example, the GUI application presented in chapter 16 of Murach’s Java SE6 uses a helper method to enable or disable the controls that are on the form.When you add a helper method to a form class, you typically add the methodnear the method declarations for the event handlers. In this figure, for example,you could add a helper method after the exitButtonActionPerformed method.

If you need to use code to initialize a control, you can add that code to theend of the constructor for the form class, after the initComponents method call.Although the code for this constructor isn’t shown in this figure, you candisplay it by clicking on the plus sign (+) that’s displayed to its left. Then, youcan enter any initialization code after the initComponents method. If, forexample, you look at the NetBeans version of the GUI application presented inchapter 16, you’ll find that it uses code to initialize the list box and comboboxes on the form. This is a common practice since it’s difficult to use theProperties window to initialize these types of controls.

In general, you can ignore the generated code for the form that’s stored inthe Generated Code region of the form. Since you must always use Design viewto modify this code, you rarely need to view it. However, if you’re curious, byall means review this code. To do that, you can expand this region by clickingon the plus sign (+) that’s displayed to its left.

If you study this code, you’ll find that it uses many of the same techniquesthat are covered in Murach’s Java SE 6. However, it also uses a few techniquesthat aren’t described in our book. For example, this code uses a layout managerknown as the GroupLayout manager that isn’t a standard part of Java. Thislayout manager is included in the swing-layout-1.0.jar file that’s automaticallyincluded in the build path for any GUI application that’s built with NetBeans.

Page 17: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 17

The source code after two event handlers have been coded

Description• You can enter the code for an event handler just as you would enter any other

code in the code editor.

• To refer to the controls that are used on the form, use the variable names that youassigned to the controls. You can review these variable names in the Navigatorwindow for the frame, and they are also listed at the end of the source code for theform.

• To import a library, code an import statement after the package statement that’s atthe start of the class.

• If you need to initialize a control, you can add code to the constructor for theclass.

• To add a helper method, you can code the method just below the event handlers.

• NetBeans shades all generated code, and you can’t manually edit this code. If youneed to change this code, use Design view to make the change.

Figure 8 How to enter the code for a form

Page 18: Jse6 Netbeans Gui Tutorial

18 How to use NetBeans for developing GUI applications

How to run and debug a form

Figure 9 shows how to run and debug a form. Since these skills are the samefor running or debugging any other class that contains a main method, youshouldn’t have any trouble with this. If you do, please refer to our “How to useNetBeans with Murach’s Java SE 6" tutorial that you can download from ourweb site (www.murach.com).

How to run a form

Since NetBeans automatically generates a main method for each form, youcan run a form by right-clicking on the .java file for the form and selecting theRun File command. In this figure, for example, I right-clicked on theFutureValueFrame.java file and selected that command. Then, NetBeans ran theform in its own application window.

To test the form, I entered valid numbers for the first three text boxes andclicked on the Calculate button. This application then displayed the result of thecalculation in the fourth text box. If you’ve read chapter 15 of Murach’s JavaSE 6, you should understand how this application works.

How to debug a form

If you need to debug a form, you can start by setting a breakpoint in thecode for the form. Then, you can right-click on the .java file for the form, selectthe Debug File command, step through code when the application reaches thebreakpoint, and check the values of your variables after each step.

Page 19: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 19

The window that’s displayed when you run the form

Description• To run a form, right-click on the .java file for the form and select the Run File command.

When you do, NetBeans will run the form in its own application window.

• To debug a form, set a breakpoint in your code, right-click on the .java file for the form,and select the Debug File command. Then, you can step through the statements andcheck the values of your variables as each statement is executed.

Figure 9 How to run and debug a project

Page 20: Jse6 Netbeans Gui Tutorial

20 How to use NetBeans for developing GUI applications

Perspective

In this tutorial, you learned how to use the Matisse GUI builder that’s availablefrom NetBeans to build the GUI for the Future Value application presented inchapter 15 of Murach’s Java SE 6. Now, you should be able to use the same skillsto build the applications presented chapters 16 and 17. If you have trouble anyapplying these skills to those applications, though, you can refer to the NetBeansversions of these applications that you can download from our web site(www.murach.com).

In my experience, there are only a few spots where applying the skills pre-sented in this chapter are tricky. First, to place a radio button in a group, you mustadd a ButtonGroup control to the form even though that control isn’t visible on theform. Then, you can use the ButtonGroup property of the radio button to specifythe group for the radio button. This creates the logical group for the radio buttons.To visually group the radio buttons, you place them on a JPanel control.

Second, to load a list or a combo box, I’ve found that it’s easiest to add code tothe constructor for the class that defines the frame. For a combo box, you can usethe addItem method of the combo box to add each item to the combo box. Usually,this means using a for statement to loop through an array of values for the dialogbox. For a list box, you can use the setListData method of the list box to populatethe list box with an array of strings.

Third, to wire several events to the same event handler, you create an eventhandler for the first event as described in figure 6. Then, if necessary, you renamethe event handler as described in figure 7. Finally, to wire other events to this eventhandler, you follow the procedure in figure 6 again, but you enter the name of thefirst event handler instead of accepting the default name that’s suggested byNetBeans.

Summary

• A GUI builder is a graphical tool that a developer can use to generate the codethat’s used to display a graphical user interface and to write the code that makesthe GUI work.

• The Matisse GUI builder is one of the most popular GUI builders for Java develop-ers. It works with Swing components and is available from the NetBeans IDE.

• A form is the window that holds the controls that comprise the graphical userinterface. When working with Swing components, a form typically inherits theJFrame class.

• Properties are the values that determine how a form and its controls will look andwork when the form is displayed.

• An event handler is a special type of method that responds to an event that’striggered when a user interacts with a form. NetBeans automatically generates thecode that wires the method for an event handler to an event.

Page 21: Jse6 Netbeans Gui Tutorial

How to use NetBeans for developing GUI applications 21

Before you do the exercise that follows…Before you do the exercise that follows, you should have the skills that arepresented in “How to use NetBeans with Murach’s Java SE 6,” which can bedownloaded from our web site. In addition, you should download theNetBeans versions of the folders and files for the applications in our bookfrom our web site and unzip them into the c:\murach\java6 folder. If this folderdoesn’t exist, you should create it. Then, the GUI versions of the applicationsfor chapters 15 through 17 in our book will be stored in this directory:

c:\murach\java6\netbeans\matisse_apps

You can also create your new applications in this directory.

Exercise 1 Use NetBeans to develop a GUIapplication

Please read chapter 15 in Murach’s Java SE 6 before you do this exercise.This exercise will guide you through the process of using NetBeans to developthe GUI application presented in chapter 15.

Start a new project and add two packages to it1. Start a new Java Application project named FutureValueGUI, but deselect the

Create Main Class option before you complete the operation.

2. Add a new package to the project named murach.ui (ui is for user interface).This is the package that the class for the Future Value form will be stored in.

3. Open the Java project named FutureValue that’s stored in the directory shownabove. Then, use the Projects tab to copy the murach.business package fromthe FutureValue project to the FutureValueGUI project that you just created.This should create the murach.business package and copy theFinancialCalculations class that’s stored in this package into your project.

Add a form and its controls to the project4. Use the procedure in figure 1 to add a form named FutureValueFrame to the

murach.ui package of the FutureValueGUI project.

5. Use the procedures in figure 2 to add, size, and align the 10 controls that areshown in this figure to the form. Then, size the form.

6. Double-click on each control, and change its text property to the one shown infigure 3.

7. Use the procedure in figure 5 to change the variable names for the four textboxes and two buttons so they can easily be referred to in your Java code.

8. Use the procedure in figure 3 to change any of the other properties for the formor controls so they will look and act the way you want them.

Page 22: Jse6 Netbeans Gui Tutorial

22 How to use NetBeans for developing GUI applications

9. Test the form, by right-clicking on the .java file for the form in the Projectswindow and selecting Run File. This should display the form so you can seehow it looks, but the form won’t work. To close the form, you can click on theClose button in the upper right corner of the form.

10. Another way to preview the form is to click on the Preview Design button inthe toolbar for Design view. Try that. This just shows that NetBeans has manyfeatures that aren’t mentioned in this introductory tutorial.

11. If you need to change anything to get the form to look the right way, do thatnow and test the form again.

Add code to the form class12. Switch to Source view and add import statements for the

java.text.NumberFormat and murach.business.FinancialCalculations classes asshown in figure 8.

13. Use the procedure in figure 6 to generate the starting code and wiring for anevent handler that handles the ActionPerformed event of the Exit button. Then,add the source code shown in figure 8 to this event handler.

14. Use the same procedure to generate the starting code and wiring for an eventhandler that handles the ActionPerformed event of the Calculate button. Then,add the source code shown in figure 8 to this event handler.

15. Run the form again. This time it should work. To prove that, test it with validentries. Then, if something doesn’t work right, fix it and test the applicationagain.

Review the code that was generated for the application16. In the code editor window, review the code for the constructor of the

FutureValueFrame class. Note that it calls an InitComponents method.

17. Click on the plus sign to the left of the Generated Code region to display theInitComponents method within this region. Then, scroll through this methodand review its code. Note that this code uses the non-standard GroupLayoutmanager rather than the Flow and Border layout managers that are described inchapter 15 of Murach’s Java SE 6. Finally, take a moment to consider howmuch work NetBeans has done for you when compared to manually writingthis code as described in chapter 15.

18. View the main method near the end of the code, and note that it creates aninstance of the FutureValueFrame class, which in turn causes the constructornear the start of the class to be executed.