Netbeans Tutorial - Part A - V2
Netbeans Tutorial - Part A - V2
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
NJO/SKA P a g e 2 | 78
Java Netbeans Tutorial
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.
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
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
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.
NJO/SKA P a g e 5 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 6 | 78
Java Netbeans Tutorial
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
NJO/SKA P a g e 8 | 78
Java Netbeans Tutorial
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.
NJO/SKA P a g e 9 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 10 | 78
Java Netbeans Tutorial
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
Your Finished GUI should now look like the following screenshot:
NJO/SKA P a g e 12 | 78
Java Netbeans Tutorial
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
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
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
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
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
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
NJO/SKA P a g e 19 | 78
Java Netbeans Tutorial
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.
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
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.
NJO/SKA P a g e 22 | 78
Java Netbeans Tutorial
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
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.
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());
}
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
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.
NJO/SKA P a g e 27 | 78
Java Netbeans Tutorial
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
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.
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:
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:
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
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];
} 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)){
} else {
NJO/SKA P a g e 32 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 33 | 78
Java Netbeans Tutorial
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
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:
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
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:
3. It will then calculate the total by adding all 5 variables into one, called total.
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)
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);
NJO/SKA P a g e 37 | 78
Java Netbeans Tutorial
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());
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.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
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.
New components
in the JFrame
NJO/SKA P a g e 40 | 78
Java Netbeans Tutorial
4.5 Testing
NJO/SKA P a g e 41 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 42 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 43 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 44 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 45 | 78
Java Netbeans Tutorial
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.
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):
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
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
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:
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.
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];
} 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)){
} else {
NJO/SKA P a g e 50 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 51 | 78
Java Netbeans Tutorial
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
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:
customerID = txtID.getText();
customerName = txtName.getText();
customerSurname = txtSurname.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);
NJO/SKA P a g e 59 | 78
Java Netbeans Tutorial
customerID = txtID.getText();
customerName = txtName.getText();
customerSurname = txtSurname.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
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) {
txtImage.setText("");
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) {
int returnval=image.showOpenDialog(this);
if(returnval==JFileChooser.APPROVE_OPTION){
txtImage.setText(filename);
BufferedImage bi;
try {
bi = ImageIO.read(file);
Image attached;
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){
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;
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.
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
(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:
try {
} catch (IOException e) {
lblRoomImage.setIcon(icon);
NJO/SKA P a g e 64 | 78
Java Netbeans Tutorial
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:
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
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:
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
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
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.
if(chkUndercoat.isSelected()){
chkUndercoatReport.setSelected(true);
}else{
NJO/SKA P a g e 68 | 78
Java Netbeans Tutorial
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
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:
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
}
}
}
NJO/SKA P a g e 70 | 78
Java Netbeans Tutorial
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
NJO/SKA P a g e 72 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 73 | 78
Java Netbeans Tutorial
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
NJO/SKA P a g e 76 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 77 | 78
Java Netbeans Tutorial
NJO/SKA P a g e 78 | 78