NMK20703 Lab Module 4 - Using Packages and GUI
NMK20703 Lab Module 4 - Using Packages and GUI
LAB MODULE 4
Objectives:
1. Able to list predefined classes in Java Swing package.
2. Able to create a GUI container using Netbeans GUI Builder Interface
3. Able to add, resize, and align components, adjust component anchoring, set component auto-resizing
behaviour and edit component properties.
JFrame JTextField
JLabel
JPanel
JCombobox
JButton
JRadioButton
JList
Getting Started
The IDE's GUI Builder makes it possible to build professional-looking GUIs without an intimate understanding of
layout managers. You can lay out your forms by simply placing components where you want them.
For descriptions of the GUI Builder's visual feedback, you can use the GUI Builder Visual Feedback Legend.
Creating a Project
For the purposes of this tutorial, we will build a simple application which is stored entirely in a single project
named “ContactEditor”.
1
NMK20703 Object-oriented Programming: Lab Module 4
The IDE creates the ContactEditor folder on your system in the designated location. This folder
contains all of the project’s associated files, including its Ant script, folders for storing sources and
tests, and a folder for project-specific metadata. To view the project structure, use the IDE’s Files
window.
1. In the Projects window, right-click the ContactEditor node and choose New > Jframe Form.
Alternatively, you can find a Jframe form by choosing New > Other > Swing GUI Forms > Jframe Form.
2. Enter ContactEditorUI as the Class Name.
Notes:
3. Enter my.contacteditor as the package. 1. Notice that the Source Packages
4. Click Finish. folder in the Projects window
contains an empty <default
The IDE creates the ContactEditorUI form and package> node.
the ContactEditorUI class within the • Because we did not check
ContactEditorUI.java application and opens (tick) the create main class
the ContactEditorUI form in the GUI Builder. when first creating new
**Notice that the my.contacteditor package replaces project.
the default package. 2. A Java container is where we will
place the other required GUI
components.
3. In this step we’ll create a
container using the JFrame
component and place the
container in a new package
Now that we’ve set up a new project for our application, let’s take a minute to familiarize ourselves with the
GUI Builder’s interface.
Note: To explore the GUI Builder interface with an interactive demo, view the Exploring GUI Builder
(.swf) screencast.
2
NMK20703 Object-oriented Programming: Lab Module 4
When we added the Jframe container, the IDE opened the newly-created ContactEditorUI form in an Editor tab
with a toolbar containing several buttons, as shown in the preceding illustration. The ContactEditor form opened
in the GUI Builder’s Design view and three additional windows appeared automatically along the IDE’s edges,
enabling you to navigate, organize, and edit GUI forms as you build them.
Design Area.
• The GUI Builder’s primary window for creating and editing Java GUI forms.
•Source button : view a class’s source code,
•Design button: graphical view of the GUI components,
• History button: access the local history of changes of the file.
•The additional toolbar buttons provide convenient access to common commands, such as choosing
between Selection and Connection modes, aligning components, setting component auto-resizing
ehaviour, and previewing forms.
Navigator.
Palette.
•A customizable list of available components containing tabs for JFC/Swing, AWT, and JavaBeans
components, as well as layout managers.
•you can create, remove, and rearrange the categories displayed in the Palette using the
customizer.
Properties Window.
•Displays the properties of the component currently selected in the GUI Builder, Navigator window,
Projects window, or Files window.
•If you click the Source button, the IDE displays the application’s Java source code in the Editor with
sections of code that are automatically generated by the GUI Builder indicated by grey areas (they
become blue when selected), called Guarded Blocks.
• Guarded blocks are protected areas that are not editable in Source view. You can only edit code
appearing in the white areas of the Editor when in Source view.
•If you need to make changes to the code within a Guarded Block, clicking the Design button returns
the IDE’s Editor to the GUI Builder where you can make the necessary adjustments to the form.
When you save your changes, the IDE updates the file’s sources.
3
NMK20703 Object-oriented Programming: Lab Module 4
Key Concepts
Free Design
In the IDE’s GUI Builder, you can build your forms by simply putting components where you want them as though
you were using absolute positioning. The GUI Builder figures out which layout attributes are required and then
generates the code for you automatically. You need not concern yourself with insets, anchors, fills, and so forth.
Visual Feedback
The GUI Builder also provides visual feedback regarding component anchoring and chaining relationships. These
indicators enable you to quickly identify the various positioning relationships and component pinning 4ehaviour
that affect the way your GUI will both appear and behave at runtime. This speeds the GUI design process,
enabling you to quickly create professional-looking visual interfaces that work.
Now that you have familiarized yourself with the GUI builder’s interface, it’s time to begin developing the UI of
our ContactEditor application. In this section we’ll take a look at using the IDE’s Palette to add the various GUI
components that we need to our form.
Thanks to the IDE’s Free Design paradigm, you no longer have to struggle with layout managers to control the
size and position of the components within your containers. All you need to do is drag and drop the components
you need to your GUI form as shown in the illustrations that follow.
Note: Refer to the Adding individual and multiple components (.swf) screencast for an interactive demo on the
section below.
Best practice: Since we’ve already added a Jframe as our form’s top-level
container, the next step is to add a couple of JPanels which will
Draw/sketch out the way you want your enable us to cluster the components of our UI using titled
interface to look before beginning to lay borders. Refer to the following illustrations and notice the
it out in GUI builder. IDE’s “drag and drop” 4ehaviour when accomplishing this.
4
NMK20703 Object-oriented Programming: Lab Module 4
To add a JPanel:
1. In the Palette window, select the Panel component from the Swing Containers category by
clicking and releasing the mouse button.
2. Move the cursor to the upper left corner of the form in the GUI Builder. When the
component is located near the container’s top and left edges, horizontal and vertical
alignment guidelines appear indicating the preferred margins. Click in the form to place the
JPanel in this location.
The JPanel component appears in the ContactEditorUI form with orange highlighting
signifying that it is selected. After releasing the mouse button, small indicators appear to
show the component’s anchoring relationships and a corresponding JPanel node is
displayed in the Navigator window, as shown in the following illustration.
Next, we need to resize the JPanel to make room for the components we’ll place within it a little later, but let’s
take a minute to point out another of the GUI Builder’s visualization features first. In order to do this we need
to deselect the JPanel we just added. Because we haven’t added a title border yet, the panel disappears. Notice,
however, that when you pass the cursor over the JPanel, its edges change to light gray so that its position can
be clearly seen. You need only to click anywhere within the component to reselect it and cause the resize
handles and anchoring indicators to reappear.
1. Select the JPanel you just added. The small square resize handles reappear around the
component’s perimeter.
2. Click and hold the resize handle on the right edge of the JPanel and drag until the dotted
alignment guideline appears near the form’s edge.
3. Release the resize handle to resize the component.
The JPanel component is extended to span between the container’s left and right margins
in accordance with the recommended offset, as shown in the following illustration.
5
NMK20703 Object-oriented Programming: Lab Module 4
Now that we’ve added a panel to contain our UI’s Name information, we need to repeat the process to add
another directly below the first for the E-mail information. Referring to the following illustrations, repeat the
previous two tasks, paying attention to the GUI Builder’s suggested positioning. Notice that the suggested
vertical spacing between the two JPanels is much narrower than that at the edges. Once you have added the
second JPanel, resize it such that it fills the form’s remaining vertical space.
6
NMK20703 Object-oriented Programming: Lab Module 4
7
NMK20703 Object-oriented Programming: Lab Module 4
Now we need to start adding the components that will present the actual contact information in our contact
list. In this task we’ll add four JtextFields that will display the contact information and the Jlabels that will
describe them. While accomplishing this, notice the horizontal and vertical guidelines that the GUI Builder
displays, suggesting the preferred component spacing as defined by your operating system’s look and feel. This
ensures that your GUI is automatically rendered respecting the target operating system’s look and feel at
runtime.
Now we’ll add a JtextField so we can get a glimpse of the GUI Builder’s baseline alignment feature.
Before proceeding further, we need to add an additional Jlabel and JtextField immediately to the right of those
we just added, as shown in the following illustration. This time enter Last Name: as the Jlabel’s display text and
leave the JtextFields’ placeholder text as it is for now.
8
NMK20703 Object-oriented Programming: Lab Module 4
To resize a JtextField:
1. Select the JtextField we just added to the right of the Last Name: Jlabel.
2. Drag the JtextField’s right edge resize handle toward the right edge of the enclosing JPanel.
3. When the vertical alignment guidelines appear suggesting the margin between the text field
and right edge of the JPanel, release the mouse button to resize the JtextField.
The JtextField’s right edge snaps into alignment with the JPanel’s recommended edge
margin, as shown in the following illustration.
1. In the Palette window, select the Label component from the Swing Controls category by
clicking and releasing the mouse button.
2. Move the cursor over the form directly below the First Name: Jlabel we added earlier. When
the guidelines appear indicating that the new Jlabel’s left edge is aligned with that of the
Jlabel above and a small margin exists between them, shift-click to place the first Jlabel.
3. While still pressing the Shift key, place another Jlabel immediately to the right of the first.
Make certain to release the Shift key prior to positioning the second Jlabel. If you forget to
release the Shift key prior to positioning the last Jlabel, simply press the Escape key.
The Jlabels are added to the form creating a second row, as shown in the following
illustration. Nodes representing each component are added to the Navigator window.
9
NMK20703 Object-oriented Programming: Lab Module 4
Before moving on, we need to edit the Jlabels’ name so that we’ll be able to see the effect of the alignments
we’ll set later.
Inserting Components
Whenever you add a component between two existing components, the GUI Builder automatically shifts them
to make room for the new component. To demonstrate this, we’ll insert a JtextField between the Jlabels we
added previously, as shown in the following two illustrations.
1. In the Palette window, select the Text Field component from the Swing Controls category.
2. Move the cursor over the Title: and Nickname: Jlabels on the second row such that the
JtextField overlaps both and is aligned to their baselines. If you encounter difficulty
positioning the new text field, you can snap it to the left guideline of the Nickname Jlabel as
shown in the first image below.
3. Click to place the JtextField between the Title: and Nickname: Jlabels.
The JtextField snaps into position between the two Jlabels. The rightmost Jlabel shifts
toward the right of the JtextField to accommodate the suggested horizontal offset.
We still need to add one additional JtextField to the form that will display each contact’s nickname on the right
side of the form.
10
NMK20703 Object-oriented Programming: Lab Module 4
To add a JtextField:
1. In the Palette window, select the Text Field component from the Swing category.
2. Move the cursor to the right of the Nickname label and click to place the text field.
The JtextField snaps into position next to the Jlabel on its left.
To resize a JtextField:
1. Drag the resize handles of the Nickname: label’s JtextField you added in the previous task
toward the right of the enclosing JPanel.
2. When the vertical alignment guidelines appear suggesting the margin between the text field
and JPanel edges, release the mouse button to resize the JtextField.
The JtextField’s right edge snaps into alignment with the JPanel’s recommended edge
margin and the GUI Builder infers the appropriate resizing 11ehaviour.
3. Press Ctrl-S to save the file.
Moving Forward
Alignment is one of the most fundamental aspects of creating professional-looking GUIs. In the previous section
we got a glimpse of the IDE’s alignment features while adding the Jlabel and JtextField components to our
ContactEditorUI form. Next, we’ll take a more in depth look at the GUI Builder’s alignment features as we work
with the various other components we need for our application.
Component Alignment
Every time you add a component to a form, the GUI Builder effectively aligns them, as evidenced by the
alignment guidelines that appear. It is sometimes necessary, however, to specify different relationships
between groups of components as well. Earlier we added four Jlabels that we need for our ContactEditor GUI,
but we didn’t align them. Now we’ll align the two columns of Jlabels so that their right edges line up.
To align components:
1. Hold down the Ctrl key and click to select the First Name: and Title: Jlabels on the left side
of the form.
2. Click the Align Right in Column button ( ) in the toolbar. Alternately, you can right-click
either one and choose Align > Right in Column from the pop-up menu.
3. Repeat this for the Last Name: and Nickname: Jlabels as well.
The Jlabels’ positions shift such that the right edges of their display text are aligned. The
anchoring relationships are updated, indicating that the components have been grouped.
Before we’re finished with the JtextFields we added earlier, we need to make sure that the two JtextFields we
inserted between the Jlabels are set to resize correctly. Unlike the two JtextFields that we stretched to the right
edge of our form, inserted components’ resizeability 11ehaviour isn’t automatically set.
11
NMK20703 Object-oriented Programming: Lab Module 4
The JtextFields are set to resize horizontally at runtime. The alignment guidelines and
anchoring indicators are updated, providing visual feedback of the component
relationships.
To set components to be the same size:
Now we need to add another Jlabel describing the JcomboBox that will enable users to select the format of the
information our ContactEditor application will display.
As in the previous examples, double-click the Jlabel to select its display text and then enter Display Format: for
the display name. Notice that when the Jlabel snaps into position, the other components shift to accommodate
the longer display text.
Baseline Alignment
Whenever you add or move components that include text (Jlabels, JtextFields, and so forth), the IDE suggests
alignments which are based on the baselines of the text in the components. When we inserted the JtextField
earlier, for example, its baseline was automatically aligned to the adjacent Jlabels.
Now we’ll add the combo box that will enable users to select the format of the information that our
ContactEditor application will display. As we add the JcomboBox, we’ll align its baseline to that of the Jlabel’s
text. Notice once again the baseline alignment guidelines that appear to assist us with the positioning.
12
NMK20703 Object-oriented Programming: Lab Module 4
The component snaps into a position aligned with the baseline of the text in the Jlabel to its
left, as shown in the following illustration. The GUI Builder displays status lines indicating
the component’s spacing and anchoring relationships.
Editing component models is beyond the scope of this tutorial, so for the time being we’ll leave the JcomboBox’s
placeholder item list as it is.
We’ve got off to a good start building our ContactEditor GUI, but let’s take a minute to recap what we’ve learned
while we add a few more of the components our interface requires.
Until now we’ve concentrated on adding components to our ContactEditor GUI using the IDE’s alignment
guidelines to help us with positioning. It is important to understand, however, that another integral part of
component placement is anchoring. Though we haven’t discussed it yet, you’ve already taken advantage of this
feature without realizing it. As mentioned previously, whenever you add a component to a form, the IDE
suggests the target look and feel’s preferred positioning with guidelines. Once placed, new components are also
anchored to the nearest container edge or component to ensure that component relationships are maintained
at runtime. In this section, we’ll concentrate on accomplishing the tasks in a more streamlined fashion while
pointing out the work the GUI builder is doing behind the scenes.
13
NMK20703 Object-oriented Programming: Lab Module 4
2. Move the cursor over the form immediately below the bottom JPanel’s E-mail title. When
the guidelines appear indicating that it’s positioned in the top left corner of the JPanel with
a small margin at the top and left edges, click to place the Jlabel.
3. Double-click the Jlabel to select its display text. Then type E-mail Address: and press Enter.
The Jlabel snaps into the preferred position in the form, anchored to the top and left edges
of the enclosing JPanel. Just as before, a corresponding node representing the component
is added to the Navigator window.
To add a JtextField:
1. In the Palette window, select the Text Field component from the Swing Controls category.
2. Move the cursor immediately to the right of the E-mail Address label we just added. When
the guidelines appear indicating that the JtextField’s baseline is aligned with the baseline of
the text in the Jlabel and the margin between the two components is suggested with a
vertical guideline, click to position the text field.
The JtextField snaps into position on the right of the E-mail Address: Jlabel and is chained
to the Jlabel. Its corresponding node is also added to the Inspector window.
3. Drag the resize handle of the JtextField toward the right of the enclosing JPanel until the
alignment guidelines appear suggesting the offset between the JtextField and JPanel edges.
The JtextField’s right edge snaps to the alignment guideline indicating the preferred
margins.
Now we need to add the Jlist that will display our ContactEditor’s entire contact list.
Since Jlists are used to display long lists of data, they typically require the addition of a JscrollPane. Whenever
you add a component which requires a JscrollPane, the GUI Builder automatically adds it for you. Because
JscrollPanes are non-visual components, you have to use the Inspector window in order to view or edit any
JscrollPanes that the GUI Builder created.
14
NMK20703 Object-oriented Programming: Lab Module 4
Component Sizing
It is often beneficial to set several related components, such as buttons in modal dialogues, to be the same size
for visual consistency. To demonstrate this we’ll add four Jbuttons to our ContactEditor form that will allow us
to add, edit, and remove individual entries from our contact list, as shown in the following illustrations.
Afterwards, we’ll set the four buttons to be the same size so they can be easily recognized as offering related
functionality.
1. In the Palette window, select the Button component from the Swing Controls category.
2. Move the Jbutton over the right edge of the E-mail Address JtextField in the lower JPanel. When the
guidelines appear indicating that the Jbutton’s baseline and right edge are aligned with that of the
JtextField, shift-click to place the first button along the Jframe’s right edge. The JtextField’s width
shrinks to accommodate the Jbutton when you release the mouse button.
3. Move the cursor over the top right corner of the Jlist in the lower JPanel. When the guidelines appear
indicating that the Jbutton’s top and right edges are aligned with that of the Jlist, shift-click to place
the second button along the Jframe’s right edge.
4. Add two additional Jbuttons below the two we already added to create a column. Make certain to
position the Jbuttons such that the suggested spacing is respected and consistent. If you forget to
release the Shift key prior to positioning the last Jbutton, simply press the Escape key.
5. Set the display text for each Jbutton. (You can edit a button’s text by right-clicking the button and
choosing Edit Text. Or you can click the button, pause, and then click again.) Enter Add for the top
button, Edit for the second, Remove for the third, and As Default for the fourth.
The Jbutton components snap into the positions designated by the alignment guidelines. The width
of the buttons changes to accommodate the new names.
15
NMK20703 Object-oriented Programming: Lab Module 4
Now that the buttons are positioned where we want them, we’ll set the four buttons to be the same size for
visual consistency as well as to clarify that they are related functionally.
Indentation
Often it is necessary to cluster multiple components under another component such that it is clear they belong
to a group of related functions. One typical case, for example, is placing several related checkboxes below a
common label. The GUI Builder enables you to accomplish indenting easily by providing special guidelines
suggesting the preferred offset for your operating system’s look and feel.
In this section we’ll add a few JradioButtons below a Jlabel that will allow users to customize the way the
application displays data. Refer to the following illustrations while accomplishing this or click the View Demo
link following the procedure to view an interactive demonstration.
1. Add a Jlabel named Mail Format to the form below the Jlist. Make certain the label is left
aligned with the Jlist above.
2. In the Palette window, select the Radio Button component from the Swing category.
3. Move the cursor below the Jlabel that we just added. When the guidelines appear indicating
that the JradioButton’s left edge is aligned with that of the Jlabel, move the JradioButton
slightly to the right until secondary indentation guidelines appear. Shift-click to place the
first radio button.
16
NMK20703 Object-oriented Programming: Lab Module 4
4. Move the cursor to the right of the first JradioButton. Shift-click to place the second and
third JradioButtons, being careful to respect the suggested component spacing. Make
certain to release the Shift key prior to positioning the last JradioButton.
5. Set the display text for each JradioButton. (You can edit a button’s text by right-clicking the
button and choosing Edit Text. Or you can click the button, pause, and then click again.)
Enter HTML for the left radio button, Plain Text for the second, and Custom for the third.
Three JradioButtons are added to the form and indented below the Mail Format Jlabel.
Now we need to add the three JradioButtons to a ButtonGroup to enable the expected toggle 17behaviour in
which only one radio button can be selected at a time. This will, in turn, ensure that our ContactEditor
application’s contact information will be displayed in the mail format of our choosing.
1. In the Palette window, select the Button Group component from the Swing Controls category.
2. Click anywhere in the GUI Builder design area to add the ButtonGroup component to the form. Notice
that the ButtonGroup does not appear in the form itself, however, it is visible in the Navigator’s Other
Components area.
3. Select all three of the JradioButtons in the form.
4. In the Properties window, choose buttonGroup1 from the buttonGroup property combo box.
Three JradioButtons are added to the button group.
17
NMK20703 Object-oriented Programming: Lab Module 4
We’ve managed to rough out our ContactEditor application’s GUI, but there are still a few things remaining to
do. In this section, we’ll take a look at a couple of other typical layout tasks that the GUI Builder streamlines.
Finishing Up
Now we need to add the buttons that will enable users to confirm the information they enter for an individual
contact and add it to the contact list or cancel, leaving the database unchanged. In this step, we’ll add the two
required buttons and then edit them so that they appear the same size in our form even though their display
text are different lengths.
4. Add another Jbutton to the left of the first, making certain to place it using the suggested
spacing along the Jframe’s bottom edge.
5. Set the display text for each Jbutton. Enter OK for the left button and Cancel for right one.
Notice that the width of the buttons changes to accommodate the new names.
18
NMK20703 Object-oriented Programming: Lab Module 4
6. Set the two Jbuttons to be the same size by selecting both, right-clicking either, and
choosing Same Size > Same Width from the pop-up menu.
The Jbutton components appear in the form and their corresponding nodes are displayed
in the Navigator window. The Jbuttoncomponents’ code is also added to the form’s source
file which is visible in the Editor’s Source view. Each of the Jbuttons are set to the same size
as the button with the longest name.
The last thing we need to do is delete the placeholder text in the various components. Note that while removing
placeholder text after roughing out a form can be a helpful technique in avoiding problems with component
alignments and anchoring relationships, most developers typically remove this text in the process of laying out
their forms. As you go through the form, select and delete the placeholder text for each of the JtextFields. We’ll
leave the placeholder items in both the JcomboBox and Jlist for a later tutorial.
Now that you have successfully built the ContactEditor GUI, you can try your interface to see the results. You
can preview your form as you work by clicking the Preview Form button ( ) in the GUI Builder’s toolbar. The
form opens in its own window, allowing you to test it prior to building and running.
19
NMK20703 Object-oriented Programming: Lab Module 4
In order for the interfaces you create with the GUI Builder to work outside of the IDE, the application must be
compiled against classes for the GroupLayout layout manager and also have those classes available at runtime.
These classes are included in Java SE 6, but not in Java SE 5. If you develop the application to run on Java SE 5,
your application needs to use the Swing Layout Extensions library.
If you are running the IDE on JDK 5, the IDE automatically generates your application code to use the Swing
Layout Extensions library. When you deploy the application, you need to include the Swing Layout Extensions
library with the application. When you build the application (Build > Build Main Project), the IDE automatically
provides a copy of the library’s JAR file in the application’s dist/lib folder. The IDE also adds each of the JAR files
that are in the dist folder to the Class-Path element in the application JAR file’s manifest.mf file.
If you are running the IDE on JDK 6, the IDE generates your application code to use the GroupLayout classes that
are in Java SE 6. This means that you can deploy the application to run on systems with Java SE 6 installed and
you do not need to package your application with the Swing Layout Extensions library.
Note: If you create your application using JDK 6 but you need the application to also run on Java SE 5, you can
have the IDE generate its code to use the Swing Layout Extensions library instead of the classes in Java SE 6.
Open the ContactEditorUI class in the GUI Editor. In the Navigator, right-click the Form ContactEditorUI node
and choose Properties in the popup menu. In the Properties dialog box, change the value of the Layout
Generation Style property to Swing Layout Extensions Library.
To run your application, right-click the project name and select Run in the context menu. In the Run Project
dialog select the main class name (my.contacteditor.ContactEditorUI if speaking about the project you have just
created) and click OK. Your application is up and running.
To run a standalone GUI application from the command line:
1. Navigate to the project’s dist folder.
20
NMK20703 Object-oriented Programming: Lab Module 4
Task 2
Question
1. Mark the following statements as TRUE or FALSE.
a. Every window has a width and height.
b. In Java, JFrame is a class.
c. To display the windows, you need not invoke a method such as setVisible.
d. In Java, the reserved word extends allows you to create a new class from an existing one.
e. The window you see displayed on your screen is a class.
f. Labels are used to display the output of a program.
g. Every GUI component you need has to be created and added to a container.
h. In Java, implements is a keyword.
i. Clicking a button is an example of an action event.
j. In a problem statement, every verb is a possible class.
k. In a problem statement, every noun is a possible method.
l. To use an object, you must know how it is implemented.
21
NMK20703 Object-oriented Programming: Lab Module 4
7. Write a GUI program that converts seconds to years, weeks, days, hours, and minutes. For this problem,
assume 1 year is 365 days.
8. Write a GUI program to convert all lowercase letters in a string to uppercase letters, and vice versa. For
example, Alb34eRt will be converted to Alb34ErT.
22