You are on page 1of 79

Java: NetBeans Tutorial Part A

A-Level Computer Science


Nilesh Jogoo
Stella Kazamia
Java Netbeans Tutorial

Contents
PART A WORKING WITH THE GUI IN JAVA ........................................................................................... 3
Chapter 1 Introduction to NetBeans IDE ............................................................................................. 3
1.1 Setting Up the Project ................................................................................................................... 3
1.2 Adding Code to the Generated Source File................................................................................... 5
1.3 Compiling and Running the Program ............................................................................................ 5
1.4 Building and Deploying the Application ........................................................................................ 7
1.5 Programming Challenge ................................................................................................................ 8
Chapter 2 GUI Building and Event Programming ................................................................................. 9
2.1 Creating a Project.......................................................................................................................... 9
2.2 Building the Front End ................................................................................................................ 10
2.3 Adding Components: Making the Front End............................................................................... 11
2.4 Renaming the Components ........................................................................................................ 12
2.5 Adding Functionality ................................................................................................................... 13
2.6 Running the Program .................................................................................................................. 16
2.7 Programming Challenge .............................................................................................................. 19
Chapter 3 GUI Building and Event Programming ............................................................................... 20
3.1 Build a New Java Project ............................................................................................................. 20
3.2 Add a JFrame form ...................................................................................................................... 22
3.3 Add Other GUI - Related Components ........................................................................................ 24
3.4 Add the Code .............................................................................................................................. 25
Chapter 4 Case Study (I) ..................................................................................................................... 27
Scenario............................................................................................................................................. 27
4.1 Setting up a new project ............................................................................................................. 28
4.2 Login Form .................................................................................................................................. 29
Create a JFrame container ............................................................................................................ 29
Adding components ...................................................................................................................... 30
Renaming the Components .......................................................................................................... 30
Making the Reset Button Work .................................................................................................... 31
Making the OK Button Work ......................................................................................................... 32
4.3 Main Form ................................................................................................................................... 34
Create a new JFrame container .................................................................................................... 34
Adding components ...................................................................................................................... 34
Making the Clear Button Work ..................................................................................................... 35

NJO/SKA P a g e 1 | 78
Java Netbeans Tutorial

Making the Submit Button Work .................................................................................................. 36


4.4 Receipt Form ............................................................................................................................... 40
Create a new JFrame container .................................................................................................... 40
Adding components ...................................................................................................................... 40
4.5 Testing ......................................................................................................................................... 41
Chapter 5 Case Study (2) .................................................................................................................... 46
Scenario............................................................................................................................................. 46
5.1 Setting up a new project ............................................................................................................. 47
Create a JFrame container ............................................................................................................ 47
Adding components ...................................................................................................................... 48
Making the Reset Button Work .................................................................................................... 49
Making the OK Button Work ......................................................................................................... 49
5.3 Main Form ................................................................................................................................... 52
Create a new JFrame container .................................................................................................... 52
Adding components ...................................................................................................................... 53
List of Components: ...................................................................................................................... 56
Making the CheckBox (chkVerify) Work ....................................................................................... 58
Making the Reset Button (btnReset) Work................................................................................... 62
Making the Attach Button (btnAttach) Work ............................................................................... 62
Making a label (lblRoomImage) display an image ........................................................................ 65
Making the comboBox (jComboBox1) display a message ............................................................ 66
Making the Undercoat checkbox (chkUndercoat) work ............................................................... 69
Making the Calculate button (btnCalculate) work ........................................................................ 70
Making the Print button (btnPrint) work (Further Improvement) ............................................... 71
Making the Print button (btnPrint) look like an image ................................................................. 72
5.4 Testing ......................................................................................................................................... 73

NJO/SKA P a g e 2 | 78
Java Netbeans Tutorial

PART A WORKING WITH THE GUI IN JAVA


Chapter 1 Introduction to NetBeans IDE

This tutorial provides a very simple and quick introduction to the NetBeans IDE workflow by walking
you through the creation of a simple "Hello World" Java console application. Once you are done with
this tutorial, you will have a general knowledge of how to create and run applications in the IDE.

1.1 Setting Up the Project


To create an IDE project:
1. Start NetBeans IDE.
2. In the IDE, choose File > New Project, as shown in the figure below.

3. In the New Project wizard, expand the Java category and select Java Application as
shown in the figure below. Then click Next.

3. In the Name and Location page of the wizard, do the following (as shown in the
figure below):

NJO/SKA P a g e 3 | 78
Java Netbeans Tutorial

In the Project Name field, type HelloWorldApp.


Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
In the Create Main Class field, type helloworldapp.HelloWorldApp.

4. Click Finish.
The project is created and opened in the IDE. You should see the following components:
The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
The Source Editor window with a file called HelloWorldApp open.
The Navigator window, which you can use to quickly navigate between elements within
the selected class.

NJO/SKA P a g e 4 | 78
Java Netbeans Tutorial

1.2 Adding Code to the Generated Source File


Since you left the Create Main Class checkbox selected in the New Project wizard, the IDE has
created a skeleton main class for you.
1. Add the "Hello World!" message to the skeleton code by replacing the line:
// TODO code application logic here
with the line:
System.out.println("Hello World!");

2. Save the change by choosing File > Save.


The code should look as follows.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloworldapp;

/**
*
* @author <your name>
*/
public class HelloWorldApp {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
1.3 Compiling and Running the Program
Because of the IDE's Compile on Save feature, you do not have to manually compile your project in
order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.
The Compile on Save feature can be turned off in the Project Properties window. Right-click your
project, select Properties. In the Properties window, choose the Compiling tab. The Compile on Save
checkbox is right at the top. Note that in the Project Properties window you can configure numerous
settings for your project: project libraries, packaging, building, running, etc.

To run the program:


Choose Run > Run Project.

NJO/SKA P a g e 5 | 78
Java Netbeans Tutorial

The next figure shows what you should now see.

Congratulations! Your program works!


If there are compilation errors, they are marked with red glyphs in the left and right margins of the
Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs in
the right margin show all of the areas of the file that have errors, including errors in lines that are
not visible. You can mouse over an error mark to get a description of the error. You can click a glyph
in the right margin to jump to the line with the error.

NJO/SKA P a g e 6 | 78
Java Netbeans Tutorial

1.4 Building and Deploying the Application


Once you have written and test run your application, you can use the Clean and Build command to
build your application for deployment. When you use the Clean and Build command, the IDE runs a
build script that performs the following tasks:
Deletes any previously compiled files and other build outputs.
Recompiles the application and builds a JAR file containing the compiled files.
To build your application:
Choose Run > Clean and Build Project.
You can view the build outputs by opening the Files window and expanding the HelloWorldApp
node. The compiled bytecode file HelloWorldApp.class is within the build/classes/helloworldapp sub
node. A deployable JAR file that contains the HelloWorldApp.class is within the dist node.

You now know how to accomplish some of the most common programming tasks in the IDE.

NJO/SKA P a g e 7 | 78
Java Netbeans Tutorial

1.5 Programming Challenge


a. Attempt to run a console application in Netbeans for example, consider your Preliminary.
b. Identify and similarities and differences to Eclipse IDE. Be ready to feedback to the class.

NJO/SKA P a g e 8 | 78
Java Netbeans Tutorial

Chapter 2 GUI Building and Event Programming

This beginner tutorial teaches you how to create a simple graphical user interface and add simple
back-end functionality. In particular we will show how to code the behaviour of buttons and fields in
a Swing form.
The application we create will be a simple but functional calculator.

2.1 Creating a Project


The first step is to create an IDE project for the application that we are going to develop. We will
name our project NumberAddition.
1. Choose File > New Project. Alternatively, you can click the New Project icon in the
IDE toolbar.
2. In the Categories pane, select the Java node. In the Projects pane, choose Java
Application. Click Next.
3. Type Lesson01 in the Project Name field and specify a path, for example, in your
home directory, as the project location.
4. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify
the location for the libraries folder.
5. Deselect the Create Main Class checkbox if it is selected.
6. Click Finish.

NJO/SKA P a g e 9 | 78
Java Netbeans Tutorial

2.2 Building the Front End


To proceed with building our interface, we need to create a Java container within which we will
place the other required GUI components. In this step we'll create a container using the JFrame
component. We will place the container in a new package, which will appear within the Source
Packages node.

Create a JFrame container


1. In the Projects window, right-click the Lesson01 node and choose New > Other.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame
Form file type. Click Next.
3. Enter Lesson01UI as the class name.
4. Enter pk.lesson01 as the package.
5. Click Finish.
The IDE creates the Lesson01UI form and the Lesson01UI class within the Lesson01 application, and
opens the Lesson01UI form in the GUI Builder. The pk.Lesson01 package replaces the default
package.

NJO/SKA P a g e 10 | 78
Java Netbeans Tutorial

2.3 Adding Components: Making the Front End


Next we will use the Palette to populate our application's front end with a JPanel. Then we will add
three JLabels, three JTextFields, and three JButtons.
Once you are done dragging and positioning the aforementioned components, the JFrame should
look something like the following screenshot.

If you do not see the Palette window in the upper right corner of the IDE, choose Window > Palette.
1. Start by selecting a Panel from the Swing Containers category on Palette and drop it
onto the JFrame.
2. While the JPanel is highlighted, go to the Properties window and click the ellipsis (...)
button next to Border to choose a border style.
3. In the Border dialog, select TitledBorder from the list, and type in Number Addition
in the Title field. Click OK to save the changes and exit the dialog.
4. You should now see an empty titled JFrame that says Number Addition like in the
screenshot. Look at the screenshot and add three JLabels, three JTextFields and
three JButtons as you see above.

NJO/SKA P a g e 11 | 78
Java Netbeans Tutorial

2.4 Renaming the Components


In this step we are going to rename the display text of the components that were just added to the
JFrame.
1. Double-click jLabel1 and change the text property to First Number:
2. Double-click jLabel2 and change the text to Second Number:
3. Double-click jLabel3 and change the text to Result.
4. Delete the sample text from jTextField1. You can make the display text editable by
right-clicking the text field and choosing Edit Text from the popup menu. You may
have to resize the jTextField1 to its original size. Repeat this step for jTextField2 and
jTextField3.
5. Rename the display text of jButton1 to Clear. (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.)
6. Rename the display text of jButton2 to Add.
7. Rename the display text of jButton3 to Exit.

Your Finished GUI should now look like the following screenshot:

NJO/SKA P a g e 12 | 78
Java Netbeans Tutorial

2.5 Adding Functionality


In this exercise we are going to give functionality to the Add, Clear, and Exit buttons. The jTextField1
and jTextField2 boxes will be used for user input and jTextField3 for program output - what we are
creating is a very simple calculator. Let's begin.

Making the Exit Button Work


In order to give function to the buttons, we have to assign an event handler to each to respond to
events. In our case we want to know when the button is pressed, either by mouse click or via
keyboard. So we will use ActionListener responding to ActionEvent.

1. Right click the Exit button. From the pop-up menu choose Events > Action >
actionPerformed. Note that the menu contains many more events you can respond to!
When you select the actionPerformed event, the IDE will automatically add an
ActionListener to the Exit button and generate a handler method for handling the listener's
actionPerformed method.

2. The IDE will open up the Source Code window and scroll to where you implement
the action you want the button to do when the button is pressed (either by mouse click or
via keyboard). Your Source Code window should contain the following lines:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//TODO add your handling code here:
}

3. We are now going to add code for what we want the Exit Button to do. Replace the
TODO line with System.exit(0);. Your finished Exit button code should look like this:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}

NJO/SKA P a g e 13 | 78
Java Netbeans Tutorial

Making the Clear Button Work


1. Click the Design tab at the top of your work area to go back to the Form Design.
2. Right click the Clear button (jButton1). From the pop-up menu select Events > Action
> ActionPerformed.
3. We are going to have the Clear button erase all text from the jTextFields. To do this,
you will add some code like above. Your finished source code should look like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}

The above code changes the text in all three of our JTextFields to nothing, in essence it is overwriting
the existing Text with a blank.

NJO/SKA P a g e 14 | 78
Java Netbeans Tutorial

Making the Add Button Work


The Add button will perform three actions.
It is going to accept user input from jTextField1 and jTextField2 and convert the
input from a type String to a float.
It will then perform addition of the two numbers.
And finally, it will convert the sum to a type String and place it in jTextField3.
Lets get started!
1. Click the Design tab at the top of your work area to go back to the Form Design.
2. Right-click the Add button (jButton2). From the pop-up menu, select Events > Action
> actionPerformed.
3. We are going to add some code to have our Add button work. The finished source
code shall look like this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
}

Our program is now complete we can now build and run it to see it in action.

NJO/SKA P a g e 15 | 78
Java Netbeans Tutorial

2.6 Running the Program


There are 3 ways you can run a Java project:
To run the program in the IDE:
1. Choose Run > Run Project (Number Addition) (alternatively, press F6).
Note: If you get a window informing you that Project Lesson01 does not have a
main class set, then you should select my. Lesson01. Lesson01UI as the main class in
the same window and click the OK button.

To run the program outside of the IDE:


1. Choose Run > Clean and Build Main Project (Shift-F11) to build the application JAR
file.
2. Using your system's file explorer or file manager, navigate to the Lesson01/dist
directory.
Note: The location of the Lesson01 project directory depends on the path you
specified while creating the project in step 3 of the Exercise 1: Creating a Project
section.
3. Double-click the NLesson01.jar file.
After a few seconds, the application should start.
Note: If double-clicking the JAR file does not launch the application, see this article for information
on setting JAR file associations in your operating system.
You can also launch the application from the command line.

To launch the application from the command line:


1. On your system, open up a command prompt or terminal window.
2. In the command prompt, change directories to the Lesson01/dist directory.
3. At the command line, type the following statement:
java -jar Lesson01.jar

Note: Make sure my.Lesson01.Lesson01UI is set as the main class before running the application.
You can check this by right-clicking the Lesson01 project node in the Projects pane, choosing
Properties in the popup menu, and selecting the Run category in the Project Properties dialog box.
The Main Class field should display my.Lesson01.Lesson01UI.

NJO/SKA P a g e 16 | 78
Java Netbeans Tutorial

Notes on Event Handling 1


This tutorial has showed how to respond to a simple button event. There are many more events you
can have your application respond to. The IDE can help you find the list of available events your GUI
components can handle:
1. Go back to the file Lesson01UI.java in the Editor. Click the Design tab to see the
GUI's layout in the GUI Builder.
2. Right-click any GUI component, and select Events from the pop-up menu. For now,
just browse the menu to see what's there, you don't need to select anything.
3. Alternatively, you can select Properties from the Window menu. In the Properties
window, click the Events tab. In the Events tab, you can view and edit events handlers
associated with the currently active GUI component.

You can have your application respond to key presses, single, double and triple mouse clicks, mouse
motion, window size and focus changes. You can generate event handlers for all of them from the
Events menu. The most common event you will use is an Action event.

How does event handling work? Every time you select an event from the Event menu, the IDE
automatically creates a so-called event listener for you, and hooks it up to your component. Go
through the following steps to see how event handling works.
1. Go back to the file Lesson01UI.java in the Editor. Click the Source tab to see the
GUI's source.
2. Scroll down and note the methods jButton1ActionPerformed(),
jButton2ActionPerformed(), and jButton3ActionPerformed() that you just implemented.
These methods are called event handlers.
3. Now scroll to a method called initComponents(). If you do not see this method, look
for a line that says Generated Code; click the + sign next to it to expand the collapsed
initComponents() method.
4. First, note the blue block around the initComponents() method. This code was auto-
generated by the IDE and you cannot edit it.
5. Now, browse through the initComponents() method. Among other things, it contains
the code that initializes and places your GUI components on the form. This code is generated
and updated automatically while you place and edit components in the Design view.

1
This theory is relevant to your theory section in Event Driven Programming.

NJO/SKA P a g e 17 | 78
Java Netbeans Tutorial

6. In initComponents(), scroll down to where it reads:


jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

This is the spot where an event listener object is added to the GUI component; in this case, you
register an ActionListener to the jButton3. The ActionListener interface has an actionPerformed
method taking ActionEvent object which is implemented simply by calling your
jButton3ActionPerformed event handler. The button is now listening to action events. Everytime it is
pressed an ActionEvent is generated and passed to the listener's actionPerformed method which in
turn executes code that you provided in the event handler for this event.

NJO/SKA P a g e 18 | 78
Java Netbeans Tutorial

2.7 Programming Challenge


a. Create a new Project which allows the user to Add, Subtract, Divide and Multiply two given
numbers.
b. Create a new Project which asks the user whether (s)he wants a salary increment. The
application will consist of two buttons: Yes and No. Each time the user attempts to move the cursor
over the Yes button, the text changes to display No instead.

NJO/SKA P a g e 19 | 78
Java Netbeans Tutorial

Chapter 3 GUI Building and Event Programming

This beginner tutorial teaches you how to create a simple graphical user interface and add simple
back-end functionality. In particular we will show how to code the behaviour of buttons and fields in
a Swing form. The application we create will be a simple but functional calculator. This chapter also
reinforces the learning from the previous chapter.

3.1 Build a New Java Project


1. To create a new project under the NetBeans IDE 6.8, go to File|New Project menu
item. A New Project wizard is displayed as shown below:

Note: NetBeans IDE allows you to create and build different projects based on different categories:
Java Application : Creates a skeleton Java Standard Edition ( SE ) project with a main class.
Java Desktop Application : Creates an application based on the Swing Application
Framework. Skeletons are offered for a basic desktop application and a database application
that makes use of the Beans Binding and Java Persistence API (JPA) libraries.
Java Class Library : Creates a skeleton Java class library without a main class.
Java Project with Existing Sources : Creates a Java SE project based on your own Java
sources.

NJO/SKA P a g e 20 | 78
Java Netbeans Tutorial

Java Free - Form Project : The free - form templates enable you to use an existing Ant script
for a project but require manual configuration.

2. On the opened New Project wizard, select the Java from the Categories pane and
click on the Java Application node from the Projects pane to create a new Java Application
Project. Click on the Next to open the New Java Application wizard:

3. Enter a desired project name, such as Lesson03 in this example, into the Project
Name box as the name for this project.
4. Select a desired location to save this project. In this example, the location is
C:\MyNetBeans. You can select any other valid folder to save your project.
5. Uncheck the Create Main Class checkbox since we do not want to use this class in
this application.
6. Keep all other default settings and click on the Finish button.

NJO/SKA P a g e 21 | 78
Java Netbeans Tutorial

3.2 Add a JFrame form


To proceed with building our interface, we need to create a Java container within which we will
place the other required GUI components. Generally, the most popular Java GUI containers include:
JFrame Form (Java Frame Form window)
JDialog Form (Java Dialog Box Form window)
JPanel Form (Java Panel Form window)

In this step, well create a container using the JFrame component. We will place the container in a
new package, which will appear within the Source Packages node.

Perform the following operations to complete this GUI adding process:


1. In the Projects window, right click on our newly created project Lesson03 node and
choose the New > JFrame Form menu item.
2. Enter JavaAppProjectFrame into the Class Name box as the class name.
3. Enter JavaAppProjectPackage into the Package box as the package name.
4. Click on the Finish button.

NJO/SKA P a g e 22 | 78
Java Netbeans Tutorial

Notes on GUI Builder Windows


The GUI Builder s various windows include:
Design Area: The GUI Builder s primary window for creating and editing Java GUI forms. The
toolbar s Source and Design toggle buttons enable you to view a class s source code or a graphical
view of its GUI components. The additional toolbar buttons provide convenient access to common
commands, such as choosing between Selection and Connection modes, aligning components,
setting component auto - resizing behavior, and previewing forms.
Inspector Window: Provides a representation of all the components, both visual and nonvisual, in
your application as a tree hierarchy. The Inspector also provides visual feedback about what
component in the tree is currently being edited in the GUI Builder, as well as allows you to organize
components in the available panels.

Palette Window: A customisable list of available components containing tabs for JFC/Swing, AWT,
and JavaBeans components, as well as layout managers. In addition, 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, Inspector window, Projects window, or Files window.
Note: Relatively speaking, AWT related GUI components are older compared with those components
defined in the Swing package. The java.awt package contains all basic and fundamental graphic user
interface components (AWT). However, the javax.swing package contains extensions of java.awt,
which means that all components in the javax.swing package have been built into a model - view -
controller (MVC) mode with more object oriented properties (Swing).

NJO/SKA P a g e 23 | 78
Java Netbeans Tutorial

3.3 Add Other GUI - Related Components


Lets add the JPanel object first in the following operational sequence:
1. Start by selecting a JPanel from the Palette window and drop it onto the JFrame.
While the JPanel is highlighted, go to the Properties window and click on the ellipsis ( . . . )
button next to the Border property to choose a border style.
2. In the Border dialog, select TitledBorder from the list, and type in Display Full Name
in the Title field, and click on the OK to save the changes and exit the dialog.
3. You should now see an empty titled JFrame that says Display Full Name JPanel
object. Now add the rest of GUI - related components, including four JLabels, two
JTextFields, and three JButtons, into this JPanel object.

Next, lets rename all added components and modify JLabel4 by setting the appropriate property for
that label in the Properties window. Perform the following operational sequence:
4. Double click on jLabel1 and change the text property to First Name.
5. Double click on jLabel2 and change the text to Last Name.
6. Double click on jLabel3 and change the text to Full Name.
7. Click on jLabel4 and click on the ellipsis (. . .) button next to the Border property to
choose a border style. In the Border dialog, select Line Border from the list, and change the
border colour to dark blue by clicking on the ellipsis (. . .) button next to the Color property,
and click on the OK to save the changes and exit the dialog. Then go to the Text property to
delete the default text JLabel4 to make this an empty label.
8. Delete the sample text from jTextField1. You can make the display text editable by
clicking on the Text field, pausing, and then clicking the Text field again. You may have to
resize the jTextField1 to its original size. Repeat this step for jTextField2.
9. Change the name of jTextField1 to FirstTextField. To do that change, right click on
the jTextField1 object and select Change Variable Name menu item from the popup menu,

NJO/SKA P a g e 24 | 78
Java Netbeans Tutorial

then enter FirstTextField into the New Name box. Click on the OK button to complete this
rename operation.
10. Perform a similar operation to change the Name property of the jTextField2 to
LastTextField, and the Name property of the jLabel4 to FullNameLabel.
11. Rename the display text of jButton1 to Display. You can edit a button s Text
property by right clicking on the button and choosing the Edit Text menu item from the
popup menu. Or you can click on the button, pause, and then click again.
12. Rename the display text of jButton2 to Clear.
13. Rename the display text of jButton3 to Exit .
14. Change the Name property of the jButton1 to DisplayButton, jButton2 to
ClearButton, and jButton3 to ExitButton, respectively.
Next, lets develop the coding for each component to connect our GUI related components with our
coding to process and response users input and display the running result.

3.4 Add the Code


In order to give function to the buttons, we have to assign an event handler to each to respond to
events. In our case, we want to know when the button is pressed, either by mouse click or via
keyboard. So we will use ActionListener responding to ActionEvent. To set up that connection, what
the developer needs to do is just to perform a double click on the selected button.

1. The function of the Exit button is to stop the running of this project and exit from
this application. (Right click on the Exit button. From the pop - up menu, choose Events >
Action > ActionPerformed. Add the appropriate code to the handler method.)
private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}

2. The function of this Clear button is to clean up all contents in two TextFields,
FirstTextField and LastTextField, respectively, to allow the user to enter a new name.
private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
FirstTextField.setText(null);
LastTextField.setText(null);
FullNameLabel.setText(null);

NJO/SKA P a g e 25 | 78
Java Netbeans Tutorial

3. The coding for this Display button ActionPerformed () event handler is simple, and
the setText () method is used to display the concatenated first and last name with a plus
symbol.
private void DisplayButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
FullNameLabel.setText(FirstTextField.getText() + " " + LastTextField.getText());
}

Center a GUI Window


The NetBeans IDE has a default location for each GUI window, the upper left corner, and will display
those windows in that location as the project runs. To make our GUI window located in the center
of the screen as the project runs, we need to put one line coding into the constructor of this class to
display our GUI window after the project runs.
Open the code window by clicking on the Source button and enter one coding line into the
constructor of this class, as shown:
public class Lesson03UI extends javax.swing.JFrame {
/**
* Creates new form Lesson03UI
*/
public Lesson03UI() {
initComponents();
this.setLocationRelativeTo(null); // set the GUI form at the center
}

A system method setLocationRelativeTo() is used to set this form at the center of the screen as the
project runs. A null argument means that no object can be referenced or relative to, and the JFrame
Form is set to the center.

NJO/SKA P a g e 26 | 78
Java Netbeans Tutorial

Chapter 4 Case Study (I)


Scenario

Pete Lumber is a self-employed plumber who finds producing estimates for a new work difficult and
time-consuming. There are often errors in his calculations which have resulted in him carrying out
work for very small profit, and sometimes losing work because his estimate was too high.

Pete has approached you to write a bespoke program for him so that his estimates become a lot
quicker and more accurate. He has expressed his interest in having a login form that would enable
only him to use the program.

The cost of a job includes these items:

Labour @ 40 /hr (per hour)


Travel @ 1 /mile (per mile)
Plastic Pipes @ 2 /m (per meter)
Copper Pipes @ 3 /m (per meter)
Chrome Pipes @ 4 /m (per meter)

He needs to be able to input:

The username and password in the Login form


The number of labour hours needed
The distance (in miles) he needs to travel, return journey
The number of meters of each type of pipe needed

The program should calculate:

Total cost for each individual element listed above


An overall total cost of the job

The program should output:

A summary of the job, including:


o Estimated labour length of time and cost
o Estimated travel distance and cost
o The selected pipes required lengths and cost
The overall cost of the job

NJO/SKA P a g e 27 | 78
Java Netbeans Tutorial

4.1 Setting up a new project


To create an IDE Java project:

1. Start NetBeans IDE


2. In the IDE, choose File > New Project, as shown in the figure below. Alternatively, you can
click the New Project icon in the IDE toolbar
3. In the New Project wizard, expand the Java category and select Java Application as shown
in the figure, and then click Next.
4. In the Name and Location page of the wizard, do the following (as shown in the figure):

In the Project Name field, type PeteLumberApp.


Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
In the Create Main Class field, type petelumberapp.Main. (You can deselect the
Create Main Class checkbox if it is selected, as you do not need it)
5. Click Finish.
The project is created and opened in the IDE. You should see the following components:

The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
The Source Editor window with a file called PeteLumberApp open.
The Navigator window, which you can use to quickly navigate between elements
within the selected class.

NJO/SKA P a g e 28 | 78
Java Netbeans Tutorial

4.2 Login Form


To proceed with building your interface, you need to create a Java container within which
you will place the other required GUI components. In this step we'll create a container using
the JFrame component. You will place the container in a new package, which will appear
within the Source Packages node.
Create a JFrame container
1. In the Projects window, right-click the PeteLumberApp node and choose New > Other.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form
file type. Click Next.
3. Enter LoginForm as the class name
4. Click Finish.

The IDE creates the Login form and the LoginForm class within the PeteLumberApp
application, and opens the LoginForm form in the GUI Builder's Design view.

NJO/SKA P a g e 29 | 78
Java Netbeans Tutorial

Adding components

Use the Palette area to populate your application's front end with a JPanel. Add four JLabels,
one JTextField, one JPasswordField, one JCheckBox and two JButtons.

Once you are done dragging and positioning the aforementioned components, the JFrame
should look something like this figure.

Renaming the Components

In this step you are going to rename the display text of the components that you have just
added to the JFrame and their variable names.
Your finished GUI should now look like the one in the following figure:

NJO/SKA P a g e 30 | 78
Java Netbeans Tutorial

Once all the components are named, the Navigator area should look like this:

Making the Reset Button Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Reset button (jButton1). From the pop-up menu select Events > Action
> actionPerformed.
3. Have the Reset button erase all text from the jTextFields. To do this, you need to add
some code. Your finished source code should look like this:

private void btnResetActionPerformed(java.awt.event.ActionEventevt){

// TODO add your handling code here:

txtUsername.setText("");

txtPassword.setText("");

txtUsername.requestFocus();

The above code changes the text in all of our fields (JTextField and JPasswordField) to
nothing; in essence it is overwriting the existing text with a blank.

NJO/SKA P a g e 31 | 78
Java Netbeans Tutorial

Making the OK Button Work

The OK button will perform three actions.


1. It is going to accept user input from jTextField1 and jPasswordField1 and store the
input in two different variables.
Click the Design tab at the top of your work area to go back to the Form Design. Right-
click the OK button (jButton2) and from the pop-up menu, select Events > Action >
actionPerformed. Then add the following variable declarations:
String username, password = "";
char[] passwordArray;
final String correctUsername = "username";
final String correctPassword = "password";

2. It will then check if the username and password match the ones stored in the program.
Add the following FOR loop and IF statement:
for (int i = 0; i< passwordArray.length; i++){

password +=passwordArray[i];

if (username.equals(correctUsername) && password.equals(correctPassword)){

} else {

3. It will show the message Login Successful if both username and password are
correct; otherwise it will show the message Invalid username/password. Add the
following code for the MessageDialog in the IF statement:
if (username.equals(correctUsername) && password.equals(correctPassword)){

JOptionPane.showMessageDialog(this, "Login Successful");

} else {

JOptionPane.showMessageDialog(this, "Invalid username/password");

NJO/SKA P a g e 32 | 78
Java Netbeans Tutorial

The completed source code should look like this:

NJO/SKA P a g e 33 | 78
Java Netbeans Tutorial

4.3 Main Form

Create a new JFrame container


1. In the Projects window, right-click the PeteLumberApp node and choose New > Other.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form
file type. Click Next.
3. Enter MainForm as the class name
4. Click Finish.
The IDE creates the Login form and the MainForm class within the PeteLumberApp
application, and opens the form in the GUI Builder's Design view.

Adding components

Use the Palette area to populate your application's front end with JPanel components.
Once you are done dragging and positioning the components, the JFrame should look
something like this figure.

NJO/SKA P a g e 34 | 78
Java Netbeans Tutorial

Making the Clear Button Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Clear button (jButton1). From the pop-up menu select Events > Action
> actionPerformed.

3. Have the Clear button erase all text from the jTextFields. To do this, you need to add
some code. Your finished source code should look like this:

private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

txtDate.setText("");

txtName.setText("");

txtSurname.setText("");

txtLabour.setText("");

txtTravel.setText("");

txtPlastic.setText("");

txtCopper.setText("");

txtChrome.setText("");

The above code changes the text in all of our JTextFields to nothing; in essence it is overwriting
the existing text with a blank.

NJO/SKA P a g e 35 | 78
Java Netbeans Tutorial

Making the Submit Button Work

The Submit button will perform three actions:


1. It is going to accept user input from the jTextFields and store the input in different
variables.
Click the Design tab at the top of your work area to go back to the Form Design. Right-
click the Submit button (jButton2) and from the pop-up menu, select Events > Action
> actionPerformed. Then add the following variable declarations:

labour = Double.parseDouble(txtLabour.getText());

travel = Double.parseDouble(txtTravel.getText());

plastic = Double.parseDouble(txtPlastic.getText());

copper = Double.parseDouble(txtCopper.getText());

chrome = Double.parseDouble(txtChrome.getText());

2. It will then perform the initial calculations by multiplying the user input by the
appropriate rate.
Add the following code:

calculateLabour = labour * labourRate;

calculateTravel = travel * travelRate;

calculatePlastic = plastic * plasticRate;

calculateCopper = copper * copperRate;

calculateChrome = chrome * chromeRate;

3. It will then calculate the total by adding all 5 variables into one, called total.

total = calculateLabour + calculateTravel + calculatePlastic +


calculateCopper + calculateChrome;

NJO/SKA P a g e 36 | 78
Java Netbeans Tutorial

4. It will link the data from the MainForm class to the ReceiptForm class. (see section D
for the design of the ReceiptForm JFrame)

ReceiptForm receipt = new ReceiptForm();

receipt.setVisible(true);

receipt.txtDate.setText(this.txtDate.getText());

receipt.txtName.setText(this.txtName.getText());

receipt.txtSurname.setText(this.txtSurname.getText());

receipt.txtLabour.setText("" + labour);

receipt.txtTravel.setText("" + travel);

receipt.txtPlastic.setText("" + plastic);

receipt.txtCopper.setText("" + copper);

receipt.txtChrome.setText("" + chrome);

receipt.lblInfoLabour.setText( "= " + calculateLabour);

receipt.lblInfoTravel.setText( "= " + calculateTravel);

receipt.lblInfoPlastic.setText( "= " + calculatePlastic);

receipt.lblInfoCopper.setText( "= " + calculateCopper);

receipt.lblInfoChrome.setText( "= " + calculateChrome);

receipt.txtTotal.setText( "" + total);

NJO/SKA P a g e 37 | 78
Java Netbeans Tutorial

The completed source code should look like this:


private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

labour = Double.parseDouble(txtLabour.getText());
travel = Double.parseDouble(txtTravel.getText());
plastic = Double.parseDouble(txtPlastic.getText());
copper = Double.parseDouble(txtCopper.getText());
chrome = Double.parseDouble(txtChrome.getText());

calculateLabour = labour * labourRate;


calculateTravel = travel * travelRate;
calculatePlastic = plastic * plasticRate;
calculateCopper = copper * copperRate;
calculateChrome = chrome * chromeRate;

total = calculateLabour + calculateTravel + calculatePlastic +


calculateCopper + calculateChrome;

ReceiptForm receipt = new ReceiptForm();


receipt.setVisible(true);

receipt.txtDate.setText(this.txtDate.getText());
receipt.txtName.setText(this.txtName.getText());
receipt.txtSurname.setText(this.txtSurname.getText());
receipt.txtLabour.setText("" + labour);
receipt.txtTravel.setText("" + travel);
receipt.txtPlastic.setText("" + plastic);
receipt.txtCopper.setText("" + copper);
receipt.txtChrome.setText("" + chrome);

receipt.lblInfoLabour.setText( "= " + calculateLabour);


receipt.lblInfoTravel.setText( "= " + calculateTravel);
receipt.lblInfoPlastic.setText( "= " + calculatePlastic);
receipt.lblInfoCopper.setText( "= " + calculateCopper);
receipt.lblInfoChrome.setText( "= " + calculateChrome);

receipt.txtTotal.setText("" + total);
}

NJO/SKA P a g e 38 | 78
Java Netbeans Tutorial

Global constants:
final double labourRate = 40;
final double travelRate = 1;
final double plasticRate = 2;
final double copperRate = 3;
final double chromeRate = 4;

NJO/SKA P a g e 39 | 78
Java Netbeans Tutorial

4.4 Receipt Form

Create a new JFrame container


1. In the Projects window, right-click the PeteLumberApp node and choose New > Other.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form
file type. Click Next.
3. Enter Receipt as the class name
4. Click Finish.
The IDE creates the Login form and the Receipt class within the PeteLumberApp
application, and opens the form in the GUI Builder's Design view.
Adding components

Use the Palette area to populate your application's front end with JPanel components.
Once you are done dragging and positioning the components, the JFrame should look
something like this figure.

ALL jTextFields not


enabled

New components
in the JFrame

NJO/SKA P a g e 40 | 78
Java Netbeans Tutorial

4.5 Testing

1. Run the software

2. Enter invalid username and/or password


Username: abcde
Password: abcde

NJO/SKA P a g e 41 | 78
Java Netbeans Tutorial

3. Enter valid username and password


Username: username
Password: password

4. Check if the Show Password checkbox works

NJO/SKA P a g e 42 | 78
Java Netbeans Tutorial

5. Enter data in the Main Form

6. Click on the Date field to auto-fill the current date.

NJO/SKA P a g e 43 | 78
Java Netbeans Tutorial

7. Click the Clear button

8. Click the Submit button

NJO/SKA P a g e 44 | 78
Java Netbeans Tutorial

9. Click the Back button

NJO/SKA P a g e 45 | 78
Java Netbeans Tutorial

Chapter 5 Case Study (2)


Scenario

Javeria Singh is an interior decorator who wants a program that is able to estimate the cost of painting
a room. Her impressive portfolio boasts over 100 plus projects. She has designed houses in different
places in UK, and the process started to become very confusing.

Javeria has approached you to write a bespoke program for her so that her estimates become a lot
quicker and more accurate. For security reasons, the decorator wants a password facility to come
with the program; if 3 unsuccessful attempts are made, program should not start.

The program needs to:

Allow the decorator to enter the height of the room (between 2 and 6 meters)
Enter the length of all 4 walls (min 1 meter, max 25 meters). For simplicity, we are considering
only square shaped rooms
o Future improvements: The program should allow the decorator to enter sizes for any
rectangular room, not just square shaped
Calculate the total area of the room
Display the total area of the room
Calculate the estimated cost of painting the room
Display the estimated cost of painting the room

The program must also allow the user to choose between 3 types of paints (quality):

Luxury @ 1.75 per sqm


Standard @ 1.00 per sqm
Economy @ 0.45 per sqm

The decorator must also be able to choose to use undercoat paint if required, which costs an
additional 0.50 per sqm.

Finally:
The program should allow the decorator to enter the potential customers details, the date of
estimate, and display an itemised bill with a total.

NJO/SKA P a g e 46 | 78
Java Netbeans Tutorial

5.1 Setting up a new project


To create an IDE Java project:

1. Start NetBeans IDE


2. In the IDE, choose File > New Project, as shown in the figure below. Alternatively, you can
click the New Project icon in the IDE toolbar
3. In the New Project wizard, expand the Java category and select Java Application as shown
in the figure, and then click Next.
4. In the Name and Location page of the wizard, do the following (as shown in the figure):

In the Project Name field, type DesignerApp.


Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
You can deselect the Create Main Class checkbox if it is selected, as you do not need
it
5. Click Finish.

5.2 Login Form


To proceed with building your interface, you need to create a Java container within which
you will place the other required GUI components. In this step we'll create a container using
the JFrame component. You will place the container in a new package, which will appear
within the Source Packages node.

Create a JFrame container


1. In the Projects window, right-click the
DesignerApp node and choose New >
Other.
2. In the New File dialog box, choose the
Swing GUI Forms category and the
JFrame Form file type. Click Next.
3. Enter LoginForm as the class name
4. Click Finish.
The IDE creates the Login form and
the LoginForm class within the
DesignerApp application, and opens
the LoginForm form in the GUI
Builder's Design view.

NJO/SKA P a g e 47 | 78
Java Netbeans Tutorial

Adding components

Use the Palette area to populate your application's front end with a JPanel. Add four JLabels,
one JTextField, one JPasswordField, one JCheckBox and two JButtons.

Your finished GUI should now look like the one in the following figure:

Each component on the JFrame should have a unique and sensible name. To change the
name, you have to right-click the component and choose Change Variable Name >Rename
dialog.

NJO/SKA P a g e 48 | 78
Java Netbeans Tutorial

Making the Reset Button Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Reset button (jButton1). From the pop-up menu select Events > Action
> actionPerformed.
3. Have the Reset button erase all text from the jTextFields. To do this, you need to add
some code. Your finished source code should look like this:

private void btnResetActionPerformed(java.awt.event.ActionEventevt){

// TODO add your handling code here:

txtUsername.setText("");

txtPassword.setText("");

txtUsername.requestFocus();

The above code changes the text in all of our fields (JTextField and JPasswordField) to
nothing; in essence it is overwriting the existing text with a blank.

Making the OK Button Work

The OK button will perform three actions.

1. It is going to accept user input from jTextField1 and jPasswordField1 and store the
input in two different variables.
Click the Design tab at the top of your work area to go back to the Form Design. Right-
click the OK button (jButton2) and from the pop-up menu, select Events > Action >
actionPerformed. Then add the following variable declarations:
String username, password = "";
char[] passwordArray;
final String correctUsername = "username";
final String correctPassword = "password";

NJO/SKA P a g e 49 | 78
Java Netbeans Tutorial

2. It will then check if the username and password match the ones stored in the program.
Add the following FOR loop and IF statement:
for (int i = 0; i< passwordArray.length; i++){

password +=passwordArray[i];

if (username.equals(correctUsername) && password.equals(correctPassword)){

} else {

3. It will show the message Login Successful if both username and password are
correct; otherwise it will show the message Invalid username/password. Add the
following code for the MessageDialog in the IF statement:
if (username.equals(correctUsername) && password.equals(correctPassword)){

JOptionPane.showMessageDialog(this, "Login Successful");

} else {

JOptionPane.showMessageDialog(this, "Invalid username/password");

NJO/SKA P a g e 50 | 78
Java Netbeans Tutorial

The completed source code should look like this:

NJO/SKA P a g e 51 | 78
Java Netbeans Tutorial

5.3 Main Form

Create a new JFrame container


1. In the Projects window, right-click the DesignerApp node and choose New > Other.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form
file type. Click Next.
3. Enter MainForm as the class name
4. Click Finish.

The IDE creates the Login form and the MainForm class within the DesignerApp
application, and opens the form in the GUI Builder's Design view.

NJO/SKA P a g e 52 | 78
Java Netbeans Tutorial

Adding components

Use the Palette area to populate your application's front end with JPanel components. In this
program you will be using the Tabbed Pane and Panel objects.

Drag and drop 3 Tabbed Pane objects in your JFrame, and then add a Panel in each and every
tab created.

Then rename the tabs so that the JFrame looks like the figure below:

NJO/SKA P a g e 53 | 78
Java Netbeans Tutorial

There is a specific layout for this program. Use the Palette area to populate your application's
front end with JPanel components, so that your end product looks something like the figures
below:
Customer Details:

Room Details:

NJO/SKA P a g e 54 | 78
Java Netbeans Tutorial

Price Quote:

NJO/SKA P a g e 55 | 78
Java Netbeans Tutorial

List of Components:

jPanel1: jPanel2:

NJO/SKA P a g e 56 | 78
Java Netbeans Tutorial

jPanel3:

NJO/SKA P a g e 57 | 78
Java Netbeans Tutorial

Making the CheckBox (chkVerify) Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Verify Details checkbox (chkVerify). From the pop-up menu select Events
> Action > actionPerformed.
3. Store the user input in new variables:

String customerName, customerSurname, customerID, customerEmail,


customerAddress, customerPhone;

customerID = txtID.getText();

customerName = txtName.getText();

customerSurname = txtSurname.getText();

customerAddress = txtAddress1.getText() + " " + txtAddress2.getText()+


" " + txtPostCode.getText()+ " " + txtCountry.getText();

customerPhone = txtPhone.getText();

customerEmail = txtEmail.getText();

4. Check if the checkbox is selected. If its selected then the data should be used as the
customer details for that specific job (Future improvement: The data can be stored in
a database once the checkbox is selected)
if(chkVerify.isSelected()){

txtIDVerified.setText(customerID);

txtEmailVerified.setText(customerEmail);

txtNameVerified.setText(customerName);

txtSurnameVerified.setText(customerSurname);

}else{

NJO/SKA P a g e 58 | 78
Java Netbeans Tutorial

5. Add code so that the data can also be used in a different JPanel. (e.g. Price Quote)
txtIDReport.setText(customerID);

txtEmailReport.setText(customerEmail);

txtNameReport.setText(customerName);

txtSurnameReport.setText(customerSurname);

txtAddressReport.setText(customerAddress);

txtPhoneReport.setText(customerPhone);

Data copied in a different JPanel

NJO/SKA P a g e 59 | 78
Java Netbeans Tutorial

6. The completed source code should look like this:

private void chkVerifyActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

customerID = txtID.getText();

customerName = txtName.getText();

customerSurname = txtSurname.getText();

customerAddress = txtAddress1.getText() + " " + txtAddress2.getText()+


" " + txtPostCode.getText()+ " " + txtCountry.getText();

customerPhone = txtPhone.getText();

customerEmail = txtEmail.getText();

if(chkVerify.isSelected()){

txtIDVerified.setText(customerID);

txtEmailVerified.setText(customerEmail);

txtNameVerified.setText(customerName);

txtSurnameVerified.setText(customerSurname);

txtIDReport.setText(customerID);

txtEmailReport.setText(customerEmail);

txtNameReport.setText(customerName);

txtSurnameReport.setText(customerSurname);

txtAddressReport.setText(customerAddress);

txtPhoneReport.setText(customerPhone);

}else{

NJO/SKA P a g e 60 | 78
Java Netbeans Tutorial

Making the Reset Button (btnReset) Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Reset button (btnReset). From the pop-up menu select Events > Action
> actionPerformed.
3. Type this code so that the textbox above the button will be cleared.
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

txtImage.setText("");

Making the Attach Button (btnAttach) Work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Attach button (btnAttach). From the pop-up menu select Events > Action
> actionPerformed.

Label with
no text
(lblImage)

NJO/SKA P a g e 61 | 78
Java Netbeans Tutorial

3. Type this code so that an image from your local area can be attached in the label.
private void btnAttachActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

JFileChooser image = new JFileChooser();

int returnval=image.showOpenDialog(this);

if(returnval==JFileChooser.APPROVE_OPTION){

File file = image.getSelectedFile();

String filename = file.getName();

txtImage.setText(filename);

BufferedImage bi;

try {

bi = ImageIO.read(file);

Image attached;

attached = ScaledImage(bi, lblImage.getWidth(),


lblImage.getHeight());

lblImage.setIcon(new ImageIcon(attached));

}catch(IOException e){

this.pack();

This is the code that enables you to locate the file in your area.
JFileChooser image = new JFileChooser();

int returnval=image.showOpenDialog(this);

if(returnval==JFileChooser.APPROVE_OPTION){

File file = image.getSelectedFile();

NJO/SKA P a g e 62 | 78
Java Netbeans Tutorial

Once the file is located, you can store the name of the file (e.g. picture.png).
String filename = file.getName();

txtImage.setText(filename);

Using the BufferedImage, you can read the image and then set the dimensions of the
image based on the size of the label. This way, the image will be scaled so that it will fit in
the space available.

BufferedImage bi;

try {

bi = ImageIO.read(file);

Image attached;

attached = ScaledImage(bi, lblImage.getWidth(), lblImage.getHeight());

lblImage.setIcon(new ImageIcon(attached));

}catch(IOException e){

this.pack();

To scale the image, you can use a user-defined function that passes the desired
dimensions of the image and returns the new image.

private Image ScaledImage(Image img, int w, int h) {

BufferedImage resizedImage = new BufferedImage(w, h,


BufferedImage.TYPE_INT_RGB);

Graphics2D g2 = resizedImage.createGraphics();

g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);

g2.drawImage(img, 0, 0, w, h, null);

g2.dispose();

return resizedImage;

NJO/SKA P a g e 63 | 78
Java Netbeans Tutorial

Making a label (lblRoomImage) display an image

Label with no text

(lblRoomImage)

1. Click the Source tab at the top of your work area to go back to the Source code
2. Locate the constructor of the Main Form class. ( public MainForm() )
3. Add the following code under the constructor:

BufferedImage img = null;

try {

img = ImageIO.read(new File( "src\\room.PNG" ));

} catch (IOException e) {

ImageIcon icon = new ImageIcon(ScaledImage(img, lblRoomImage.getWidth(),


lblRoomImage.getHeight()));

lblRoomImage.setIcon(icon);

NJO/SKA P a g e 64 | 78
Java Netbeans Tutorial

Making the comboBox (jComboBox1) display a message

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the comboBox (jComboBox1). From the pop-up menu select Events > Action
> actionPerformed, and type the following code:

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {


length = Double.parseDouble(txtLength.getText());
width = Double.parseDouble(txtWidth.getText());
height = Double.parseDouble(txtHeight.getText());
txtLength.setText("" + length);
txtWidth.setText("" + width);
txtHeight.setText("" + height);
txtHeightDuplicate.setText("" + height);

This code will store the user input in different variable so they can be used later on.

3. Then, you need to store the selected item from the comboBox so that you can perform
the calculations.
Reminder:
The program must also allow the user to choose between 3 types of paints (quality):
Luxury @ 1.75 per sqm
Standard @ 1.00 per sqm
Economy @ 0.45 per sqm

final double luxuryRate = 1.75;


final double standardRate = 1;
final double economyRate = 0.45;

JComboBox list = (JComboBox) evt.getSource();


String selection = (String) list.getSelectedItem();
switch (selection) {
case "Luxury":
cost = luxuryRate;
break;

case "Standard":
cost = standardRate;
break;

case "Economy":
cost = economyRate;
break;

NJO/SKA P a g e 65 | 78
Java Netbeans Tutorial

4. When calculating the area of the room, you need to consider 5 walls:

(1 x ceiling) + (4 x walls) = 5 sides


DO NOT COUNT THE FLOOR!!!

Replace the code added for the switch case, with the following calculations:

switch (selection) {
case "Luxury":
cost = luxuryRate;
lblPaintTypeCost.setText( "Luxury: 1.75 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 *
width * height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

case "Standard":
cost = standardRate;
lblPaintTypeCost.setText( "Standard: 1.00 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 *
width * height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

case "Economy":
cost = economyRate;
lblPaintTypeCost.setText( "Economy: 0.45 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 *
width * height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

NJO/SKA P a g e 66 | 78
Java Netbeans Tutorial

5. The completed source code should look like this:


private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
length = Double.parseDouble(txtLength.getText());
width = Double.parseDouble(txtWidth.getText());
height = Double.parseDouble(txtHeight.getText());
txtLength.setText("" + length);
txtWidth.setText("" + width);
txtHeight.setText("" + height);
txtHeightDuplicate.setText("" + height);

JComboBox list = (JComboBox) evt.getSource();


String selection = (String) list.getSelectedItem();
switch (selection) {
case "Luxury":
cost = luxuryRate;
lblPaintTypeCost.setText( "Luxury: 1.75 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 * width
* height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

case "Standard":
cost = standardRate;
lblPaintTypeCost.setText( "Standard: 1.00 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 * width
* height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

case "Economy":
cost = economyRate;
lblPaintTypeCost.setText( "Economy: 0.45 per square meter" );
estimatedCost = (length * width) + (2 * length * height) + (2 * width
* height) * cost;
lblCost.setText( "Estimated cost: " + estimatedCost);
break;

txtLengthReport.setText("" + length);
txtWidthReport.setText("" + width);
txtHeightReport.setText("" + height);
cbxValueReport.setSelectedItem((String)selection);

NJO/SKA P a g e 67 | 78
Java Netbeans Tutorial

Making the Undercoat checkbox (chkUndercoat) work

1. Click the Design tab at the top of your work area to go back to the Form Design
2. Right click the Undercoat checkbox (chkUndercoat). From the pop-up menu select
Events > Action > actionPerformed.
3. Check if the checkbox is selected. If its selected then a message should be displayed
to the user Additional 0.50 per square meter and the additional cost.

private void chkUndercoatActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

if(chkUndercoat.isSelected()){

lblUndercoatCost.setText( "Additional 0.50 per square meter ( + " +


(((length * width) + (2 * length * height) + (2 * width * height)) * 0.50) +
")");

chkUndercoatReport.setSelected(true);

}else{

lblUndercoatCost.setText( "No extra charges!" );

NJO/SKA P a g e 68 | 78
Java Netbeans Tutorial

Making the Calculate button (btnCalculate) work

The text fields cannot be edited. Autofilled based on the user input from the previous tabs.

1. Right click the Calculate button (btnCalculate). From the pop-up menu select Events >
Action > actionPerformed.
2. Enter the following code:

NJO/SKA P a g e 69 | 78
Java Netbeans Tutorial

Making the Print button (btnPrint) work (Further Improvement)

1. Right click the Calculate button (btnCalculate). From the pop-up menu select Events >
Action > actionPerformed.
2. In this method, you need to use new libraries (PrinterJob and Printable) in order to use the
print features of a Windows/ Linux/ MacOS machine. Try the following code:

private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {


PrinterJob job = PrinterJob.getPrinterJob();
job.setJobName( "Customer Report" );

job.setPrintable (new Printable() {


public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
panelPrint.paint(g2);
return Printable.PAGE_EXISTS;
}
});

boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
}
}
}

NJO/SKA P a g e 70 | 78
Java Netbeans Tutorial

Making the Print button (btnPrint) look like an image

1. Drag and drop a new JButton in your JFrame

2. Click on the button, and go to the Properties. Change the foreground colour into a
light blue, the icon into the image that you want to display, and the text into Print.

3. Click on the button, and go to the Properties. Scroll down into the Other Properties
section and untick the boarderPainted and the contentAreaFilled.

NJO/SKA P a g e 71 | 78
Java Netbeans Tutorial

5.4 Testing

1. Run the software

2. Enter invalid username and/or password


Username: abcde
Password: abcde

NJO/SKA P a g e 72 | 78
Java Netbeans Tutorial

3. Enter valid username and password


Username: username
Password: password

4. Check if the Show Password checkbox works

NJO/SKA P a g e 73 | 78
Java Netbeans Tutorial

5. Enter data in the Main Form (Customer Details)

6. Select the checkbox Verify Details

NJO/SKA P a g e 74 | 78
Java Netbeans Tutorial

7. Click on the Attach button to add an image for that customer. Select an image in your area
and then select Open.

NJO/SKA P a g e 75 | 78
Java Netbeans Tutorial

8. Enter data in the Main Form (Room Details)

9. Select different types of paint from the comboBox.

NJO/SKA P a g e 76 | 78
Java Netbeans Tutorial

10. Select the Price Quote tab.

NJO/SKA P a g e 77 | 78
Java Netbeans Tutorial

11. Click on the Calculate button

12. Click on the Print button

NJO/SKA P a g e 78 | 78

You might also like