Java Swing Module Activity
Java Swing Module Activity
DCIT 50
Lesson1. Introduction to Java Swing
Discussion:
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Window Toolkit) API and entirely written in java.
Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich set of widgets.
It includes package lets you make GUI components for your Java applications, and It is platform
independent.
The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit. You can use the Java GUI components like button, textbox, etc. from the
library and do not have to create the components from scratch.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful components
such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
Container classes are classes that can have other components on it. So for creating a GUI,
we need at least one container object. There are 3 types of containers.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to
organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has
to be displayed. It is not a fully functioning window like the Frame.
1. Menu Bar – use to show tools not available in your work area.
2. Task Bar – use as shortcut on some of the events of the menu bar.
3. Project Explorer window – where you can see your project lists. If you cannot see this
window, then you can go to Window Menu and choose Projects as shown below. Or
press Ctrl then 1 for the shortcut
4. Toolbox – sometimes called Palette in java. The Toolbox window contains all the
controls you can use to build your application’s interface. If you cannot see this
window, then you can navigate to the menu bar as shown below.
5. Work Area – this is where you do your application development (design and coding). This is
your form design.
6. Properties - This window (also known as the Properties Browser) displays all the properties
of the selected component or control and its settings. Every time you place a control on a
form, you switch to this window to adjust the appearance of the control. If you cannot see
this window then you can navigate to the menu bar as shown below.
Summary
In this lesson, you learned the concept of Java graphical user interface programming design
using Swing. Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a
rich set of widgets. It includes package lets you make GUI components for your Java
applications, and It is platform independent.
Also, in this lesson you learned the different components of NetBeans Integrated
Development Environment (IDE) especially toolbox, project explorer window, the work area
among other things. You should familiarize yourself with the IDE as one of your foundations in
building Java application.
Lesson 2. Layout Managers
Layout Managers
Absolute layout
Free Design
Border Layout
Box Layout
Card Layout
Flow layout
Grid Bag Layout
Grid Layout
Null Layout
OverLay Layout
When you create a JFrame, you can set a layout you want in the form. This can be done by
right clicking the JFrame form, select Set Layout, then select the layout you want int the form
as shown in the screenshot below.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:
Example:
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.
Summary
Absolute layout
Free Design
Border Layout
Box Layout
Card Layout
Flow layout
Grid Bag Layout
Grid Layout
Null Layout
OVerLay Layout
Each of the types has its own layout that can arrange your components. With this in mind, you
should now have the idea which of them can be used to better solve your application
needs.
Lesson3. Java Swing GUI
The first step is to create an IDE project for the application that we are going to develop. We
will name our project GUI
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 as shown below.
3. Type GUI in the Project Name field and specify a path, for example, in your home
directory, as the project location as shown below
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.
Create a JFrame container
1. In the GUI Project window, right-click the Source Packages node and choose New >
JFrame as shown below
2. Click Finish.
The IDE creates the Exercise form and the Excercise class within the GUI application/project
as shown below
Note If you do not see the Palette window in the upper right corner of the IDE, choose
Window > Palette.
In this step we are going to rename the display text of the components that were just added
to the JFrame.
1. Right click jLabel1, choose Edit Text and change the text property to Name:
2. Right click jLabel2, choose Edit Text and change the text property to Surname:
3. Right click jLabel3, choose Edit Text and change the text property to Display:
4. Delete the sample text from jTextField1. Follow the steps done in Step 1, just delete the
text on it. 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 Display. (You can edit a button's text by right-
clicking the button and choosing Edit Text. Or you can click the button, then pause,
and then click again.)
To resize a Component
3. When you think it is the size you want, release the mouse button to resize the JTextField.
Your Finished GUI should now look like the following screenshot:
Exercise 3: Adding Functionality
In this exercise we are going to give functionality to the Display button. The jTextField1 and
jTextField2 will be used for user input and jTextField3 to display the user input.
3. We are now going to add code for what we want the Display Button to do and that is
to display the user entered in JTextField3. Replace the TODO line with the code in box
below.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
3. After pressing OK, you should see the screenshot as shown below
4. Type Jose and Rizal on the name and surname respectively. Then click the display button.
You should see the screenshot as shown below
Component explanations used in this example
JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must
have a frame to have the components added to it.
JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If you
want to display a string or an image on a frame, you can do so by using labels.
JTextField – Used for capturing user inputs, these are the text boxes where user enters the data.
JButton – A button is an instance of JButton class. In the above example we have a button
“Display”.
Tip. Naming a component is important for others to know what that component is all about
without going through the form designer. In this case we will follow below naming convention
JFrame – starts with frm
Jlabel – starts with lbl
JTextField – starts wth txt
JButton – starts with btn
2. right click the label name and choose Change Variable Name as shown below
Note. Follow the same steps on the remaining labels, textboxes and buttons.
Step 3. Open the source code by double clicking the Display button. Notice that
Java will automatically sync the component name in your code as shown in the screenshot
below.
Exercise. Design a JFrame as shown in the screenshot below. The program will allow the user
to enter two numbers. When the user click the Compute button, it will display the sum. When
the user click the Clear button, it will remove/erase all the data in JTextFields.
Note. remember the naming rules of component
Solution.
Step 1. Create a JFrame, and name it Calculator. Drag three JLabels, three JTextFields
and two JButtons. Make appropriate labels and names on each of the components.
Note. Red labels as shown above are the name of the components. Going forward you
now know how to name components based on the naming conventions mentioned.
Step 2. Double click Compute button and enter the code in red box as shown below
In this code, we are using + operator to add number1 and number2. Integer.parseInt is a
method in converting the data entered to number.
Note. if you will see btnComputeActionPerformed, it means that this is the code for
button
btnCompute. This is one of the advantages of following a naming convention.
Step 3. Double click Clear button and enter the code in red box as shown below
Step 4. Run the Calculator program. If you have more than one program in your project, you
need to right click the Calculator file in your project window and choose run file as shown
below.
Step 5. Type two numbers in number1 and number2 textbox and click Compute button. You
should see the sum on the sum textbox. Click Clear button and the numbers will erase. Your
output should be same as screenshot below.
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm
dialog box and input dialog box. These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.
Constructor Description
Methods Description
void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.
Example
Step 1. Create a JFrame, name it as OptionDialog as shown below
Note
you should notice the word “MessageBoxExampes” in the JFrame. This is the title. You can
modify the title of the JFrame by its propery “title” as shown below.
by following the naming conventions that Button component start with btn so your
components name will be btnOKCancel, btnYesNo, btnSimpleDialog,
bytnYesNoCancel
Step 2. Double click OK Cancel button and type the code in red box below
private void btnOKCance1ActionPerformed(java_awt_event_ActionEvent evt)
II TODO add your handling code here:
int n = JOptionPane.showConfirmDialog(
null,
"Click OK or Cancel" ,
"OK or Cancel",
JOptionPane.OK_CANCEL_OPTION);
if( n == JOptionPane.OK_OPTION){
JOptionPane.showMessageDialog(null,"OK");
}
else
{
JOptionPane.showMessageDialog(null,"Cancel");
}
Step 3. Double click Yes No button and type the code in red box below.
if (n == JOptionPane.YES_OPTION)
JOptionPane.showMessageDialog(null, "You click YES");
else if (n == JOptionPane.NO_OPTION)
JOptionPane.showMessageDialog(null, "You click NO");
Step 4. Double click Yes No Cancel l button and type the code in red box below
Step 5. Double click Simple Dialog button and type the code in red box below
Step 6. In the source code, go to the top and add the code in red box below. This is needed
for the JOptionPane to work.
Step 7. Run your program and click each buttons. You should be able to see pop up
windows or message boxes.
Tip. Use JOptionPane when verifying user response like if they want to delete the records or update
the records or proceed with the transactions.
Explanations
The showMessageDialog () method is used to display a dialog box with a message prompt and an
ok button.
Here the parameters are,
Parent -dialog is centered over the parent component. if a parent is Null, the dialog is
Centred on the screen.
message- message to display on a dialog box
title- display the title from the dialog box
message type - one of
ERROR_MESSAGE,INFORMATION_MESSAGE,QUESTION_MESSAGE,PLAIN_MESSAGE
The showConfirmDialog() is used to display a dialob box with a message and a choice of
buttons. Here the parameters are
Component – The first parameter is a Component which determines the Frame in
which the dialog is displayed; if null, or if the parentComponent has no Frame, a
default Frame is used.
Object – The second parameter can be any Object. (In some older versions of Java
you might get a compiler error when using primitive types directly)
String – The third parameter is a String placed as the title of the confirmDialog window.
int – The int that follows the String is the OptionType. The different OptionTypes for
JOptionPane, are:
o DEFAULT_OPTION
o YES_NO_OPTION
o YES_NO_CANCEL_OPTION
o OK_CANCEL_OPTION
int – The next int is the MessageType. The different MessageTypes for JOptionPane, are:
o ERROR_MESSAGE
o INFORMATION_MESSAGE
o WARNING_MESSAGE
o QUESTION_MESSAGE
o PLAIN_MESSAGE
Icon – The last parameter is an Icon that is displayed inside the dialog and overrides the
default MessageType icon.
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It
allows the editing of a single line of text. It inherits JTextField class.
Tip. Since this is component acts like a JTextField, then the naming convention will start also with txt
Exercise. Create a login JFrame that allows the user to enter his/her credentials (username
and password). Assuming username is abc and password is 123. Validate the credentials
and display appropriate message like “welcome” if the data entered is valid or “invalid
account” if the data entered is incorrect.
Solution.
Step 1. Create a JFrame and name it as Login. Design the form as shown below.
Note. Before doing step 2. You need to change the components name. remember the
naming convention.
Tip. If you will not use a component for processing, then no need to change the component
name. example here. The labels are being used to display only, you will not use it like
displaying data during button click or processing so no need to change the name.
Step 2. Double click Login button and type the code as shown in red box below.
Step 3. Run the program. Type on the textboxes. Notice that the password field character is
masked to
******. Type abc and 123 for username and password respectively and you will see a pop up
message
“welcome” as shown below.
Try to enter different data. you should see invalid account pop up message.
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Note. here we did not change the name of JCheckBox component so the default name is
jCheckBox1. Step 2. Double click the Check button and type the code in as shown below
Step 3. Double click the Uncheck button and type the code as shown below
Step 4. Double click the Verify Checkbox Status and type the code in red box as shown below
Step 5. Run the JFrame. Click check or uncheck buttons. You should notice that the
jCheckbox1 is either have check or uncheck mark. Click the Verify CheckBox Status button.
You should see the output as shown below
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options.
This program will allow you to enter two numbers and choose either you want to add, subtract,
multiply and divide. When you click the compute button, it will display the result in the result
text box.
Note. as naming convention, you should name JRadioButton to opt. so here your four
JRadionButton should be named
optAdd, optSubtract, optMultiply, optDivide respectively
Step 2. Run the JFrame. and click on the option buttons. Notice that you can check it all as
shown in the screenshot below.
How to solve? Put the button group.
Step 3. Go to the JFrame form design and put the button group as shown below
Note. you cannot see the button group in the form design.
Step 4. Click the add option and go to the properties window. Choose buttonGroup and
select buttonGroup1, as shown below
Do the same for subtract, multiply and divide
Step 5. Run the JFrame and click on each option buttons. Notice that you can now only
choose one as shown below, otherwise go back to Step 4.
Step 6. Double click the Compute button and the code in red box as shown below.
Step 7. Run the JFrame program. Enter two numbers, choose the math operation and click
the compute button. You should see the output as shown below.
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user
can choose either one item or multiple items. It inherits JComponent class.
Methods Description
Note. Before doing step 2, rename the JListBox component to lstProducts and the You
Selected label to lblDisplay.
Step 2. We will modify the list box data. Instead of Item 1, Item 2…Item 5, we will put Shoes, Socks,
Pants and Shirts. In order to do that, first select the list box, and in the properties choose Model as
shown below
Note. as you have done in our previous exercises, make sure you are under the properties of
the component as shown in the green box in the screenshot.
Step 3. In the screenshot in Step 2, click the ellipsis as shown in the red box. You should see the
screen as shown below.
Step 4. Delete Item 1 to 5 and replace it with Shoes, Socks, Pants and Shirts. Then Click OK.
Step 5. Your JFrame now should the same as screenshot below
Step 6. Bind the listbox to an event. When a user selected a product, we will display the
selected on in the label. Right click the listbox, choose event, PropertyChange then
propertyChange as shown below.
Step 7. In the source code window of the list box, type the code in red box as shown below.
To get the data in the lstProducts, you need to invoke getSelectedValuesList method. If you
want to get the index number then you will invoke getSelectedIndex() method.
Step 8. Run the program. Select a product on the list, and you should see the value and list on the
label display as shown below.
Another example, this time we will hardcode that value of the list. This is important especially if
the data is coming from a data source like database, text files, among other things.
Step 1. Create another JFrame, this time name it ListCountry. Design the form as shown below.
Step 2. When you run the program, the listbox should contain list of countries. For this, in the
JFrame form click the Source Tab, beside the Design Tab, as shown below.
Step 3. In the source tab, type the code as shown in red box below.
Explanation
class ListCountry is the class name of the JFrame. this is the same as when you create a
class in your basic console application.
DefaultModel - provides a simple implementation of a list model, which can be used to
manage items displayed by a JList control.
AddElement – this is how you add data in the DefaultModel
lstCountry.setModel(lst) – this means that you are binding the lst data into your list control
Step 4. Run the JFrame program. You can now see that your List have contents as shown in
the screenshot below.
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits JComponent class.
Methods Description
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
Example
Step 1. Create a JFrame and name it Country. Design the form as shown below.
Step 4. Run the JFrame program. You can see in the combo box the list of countries you
added in Step 3, as shown in the screenshot below.
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Tip. For the naming convention, we will start with tbl.
Example.
Step 1. Create a JFrame and name it TableSample. Drag a component table in the form. Your
JFrame should be shown as screenshot below
Step 2. Lets modify the table and put some data on it. Click the table component and in the
properties, select model as shown in the screenshot below
Step 3. In the table model form, go to table settings and modify the Title as shown in the
screenshot below.
Step 4. In the table model form, go to Default Values tab and modify the data as shown in
the screenshot below. Note follow the steps as indicated.
Step 5. Run the JFrame program, you can now see the output showing a data tables as shown
in the screenshot below.
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
In order to put the border on the panel, you need to modify its border properties as shown below.
Java JTabbedPane
Example
Step 1. Create a JFrame and name it TabExample. Drag a Tabbed Pane in the form as shown
in the screenshot below.
Step 2. In the Tabbed Pane component, you can see that it is blank. No tab on it where you
can put your components. To do this, select the tabbed pane, and then drag a panel
above the square as shown in the red line. You should see a tab1 on it.
Note. Add two more tabs by dragging a panel beside the tab 1.
Step 3. Lets modify the text of tab1 to add, tab 2 to subtract and tab 3 to multiply. Modifying the
text
is the same as what you have don’t with JLabel, JTextField, etc..
Step 4. Add three labels, three textboxes and one button to each of the tabs.
Step 5. Run the JFrame form, and you should see that each tab can handle different
components as needed as shown in the screenshots below.
Practice Program
1. Create a JFrame program that allow the user to enter three grades. If one of them failed
then it is failed, otherwise compute and display the average. Create a method to display
the average.
Note. Passing grade = 60
2. Create a JFrame program that allow the user to choose if an employee is regular or
contractual and also allow user to enter a salary. If the employee is regular, then add 100 to
the entered salary. If the employee is contractual then add 50 to the entered salary. Display
the salary in a dialog box.
Note. use Radio Button
3. Create a login program that allow the user to enter his/her username and password as
shown in the screenshot below. Sample screenshot as shown below.
Write a program that asks for the number of checks written for the month. The program should then
calculate and display the bank's services fees for the month.
6. Write a program to calculate and print the Electricity bill of a given customer. Allow the user to
enter customer id., name and unit consumed and display the total amount to pay to the
customer. The charge are as follow
Unit Charge/Unit
1 to199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00
If bill exceeds 400 then a surcharge of 15% will be charged.
7. Create a ticketing system where a user will be allowed to choose what movie he/she wants
to watch. You should display the movie price, movie time and movie rating.
8. Write a program that determines a student’s grade. The program will read three scores
and determine the grade based on the following rules:
Average Rating
average score =90% A
average score >= 70% and <90% B
average score>=50% and <70% C
average score<50% F
Display the corresponding rating.
9. One of the challenges in a company is to track the inventory of different product lines.
As a programmer, you are required to allow the user to choose a product in the list, and
display the quantity available of that product. The user then be allowed to enter the request
quantity which your program subtract with the available quantity to get the remaining
inventory. Validate your data.
Note. since you don.’t have a database, follow the product and its corresponding available
quantity
as shown below.
Product Name Available Quantity
Ballpen 100
Notebook 200
Bag 50
Activity Program
Instructions:
Provide the following programs. Follow the criteria for each program.
You should design the GUI of each program. Your OWN design. Each interface should
contain colors and different fonts (explore each component properties to customize).
Your output should contain the screenshot of the interface and the code of each
button.
Put your output in a single PDF File, with a file name of (SURNAME,FIRSTNAME, SECTION).
Upload your output in the Gdrive link provided. Make sure to put it in your section
folder.
https://drive.google.com/drive/folders/1E7qcjQJgWk5NGP6H1i6nBoXWWtz9u8SY?usp=
sharing
Anyone with the same design will be marked both ZERO SCORE.
The score will be a total of 150 points for 3 items.
The deadline for this activity is on January 5, 2024, 12 PM.
1. Create a JFrame program that allows the user to enter two numbers and display the
result based on the mathematical operators as shown below.
2. In relation to program number 1. Display the result in a MESSAGE DIALOG for each button. The
jTextfield result should be removed.
3. As a programmer, you are required to create an ordering system where the user can
choose what products he/she wants. After the user choose the product(s), you will
display the total price as shown in the screenshot below.