0% found this document useful (0 votes)
99 views

Java Swing Module Activity

This lesson introduces Java Swing GUI programming. It discusses creating a Java project in NetBeans IDE and building a simple GUI interface with components like labels, text fields and buttons. The interface is designed using different layout managers. Specifically, it demonstrates how to add components to a JFrame container, rename their display text, and position them on the frame. The next steps will include adding backend functionality to the buttons and text fields to retrieve and display user input.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Java Swing Module Activity

This lesson introduces Java Swing GUI programming. It discusses creating a Java project in NetBeans IDE and building a simple GUI interface with components like labels, text fields and buttons. The interface is designed using different layout managers. Specifically, it demonstrates how to add components to a JFrame container, rename their display text, and position them on the frame. The next steps will include adding backend functionality to the buttons and text fields to retrieve and display user input.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

JAVA SWING

DCIT 50
Lesson1. Introduction to Java Swing

Discussion:

What is Java Swing

 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.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

Java AWT Java Swing

AWT components are platform-dependent. Java swing components are platform-


independent.

AWT components are heavyweight. Swing components are lightweight.

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.

AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

What is a container class?

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.

Java Swing Integrated Development Environment (IDE)

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

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:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Java CardLayout

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

In this lesson, you learned different types of layout managers, namely

 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

Introduction to GUI Building


We will create a simple graphical user interface and add simple back-end functionality. In
particular we will go steps by steps on how to code the behavior of buttons and fields in a
Swing form, JFrame in particular. We will work through the layout and design of a GUI and
add a few buttons and text fields. The text fields will be used for receiving user input and also
for displaying the program output. The button will initiate the functionality built into the front
end. The application we create will be a simple display of information entered by the user.

Exercise 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 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

Note. Deselect the Create Main Class checkbox if it is selected.


3. Click Finish. For now, you should see a blank project as shown below

Exercise 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.
Create a JFrame container

1. In the GUI Project window, right-click the Source Packages node and choose New >
JFrame as shown below

1. Enter Exercise as the class name

2. Click Finish.
The IDE creates the Exercise form and the Excercise class within the GUI application/project
as shown below

Adding Components: Designing the Front End


 Next we will use the Palette window to populate our application's front end. We will
add three JLabels, three JTextFields, and a JButton.
 In the palette window, drag and drop three JLabels, three JTextFields, and a JButton in
to the JFrame.
 Once you are done dragging and positioning the aforementioned components, the
JFrame should look something like the following screenshot below.

Note If you do not see the Palette window in the upper right corner of the IDE, choose
Window > Palette.

Renaming the Components display

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

1. Select the component here JTextField as example


2. Drag the JTextField's right edge to resize

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.

Making the Display Button Work


In order to give function to the Display button, 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. Double click the Display button.
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 jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

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)
{

String name = jTextField1.getText();


String surname = jTextField2.getText();
//put the data in JTextField3
jTextField3.setText(name + " " + surname);
}
Code explanation.
 String name and String surname = variable that will store the user entry
 jTextField1, jTextField2, jTextField3 = these are names of the component.
 getText = method to get the data entered by the user in the JTextField component.
example. String name = jTextField1.getText (get the data entered by the user in
jTextField1 and put it in variable name)
 setText = method to set or put the data in the JTextField component
example. jTextField3.setText(name) – means you are putting the data, here the
name content, in the jTextField3 component.
Exercise 4: Running the Program

To run the program in the IDE:


1. Choose Run > Run Project (GUI) (alternatively, press F6).
2. When you see the screenshot below, select the JFrame class, and click OK.

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

Using the screenshot below, we should name our


components as For the three labels
 lblName
 lblSurname
 lblDisplay
For the three input box
 txtName
 txtSurname
 txtDisplay

For the button display


 btnDisplay

Renaming the Components name – Option 1


Follow the steps below
1. Go the to the JFrame form

2. right click the label name and choose Change Variable Name as shown below

3. Type lblName as shown below. Then click ok


Note. Follow the same steps on the remaining labels, textboxes and buttons
Step 4. 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.

Renaming the Components name – Option 2 (Using Properties window)

Follow the steps below


1. Go the to the JFrame form
2. Click the label name. in the properties window, go to the code tab, select variable
name and type lblName or any name that you want 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

 In this code, we are setting space to txtNumber1 and txtNumber2 component by


using the setText method.

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.

JOptionPane class declaration

public class JOptionPane extends JComponent implements Accessible


Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object It is used to create an instance of JOptionPane to display


message) a message.

JOptionPane(Object It is used to create an instance of JOptionPane to display


message, int messageType a message with specified message type and default
options.

Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new


parentless JDialog with the specified
title.
static void showMessageDialog(Component It is used to create an information-
parentComponent, Object message) message dialog titled "Message".

static void showMessageDialog(Component It is used to create a message dialog


parentComponent, Object message, String title, with given title and messageType.
int messageType)

static int showConfirmDialog(Component It is used to create a dialog with the


parentComponent, Object message) options Yes, No and Cancel; with the
title, Select an Option.

static String showInputDialog(Component It is used to show a question-message


parentComponent, Object message) dialog requesting input from the user
parented to parentComponent.

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.

private void btnYesNoActionPerformed(java_awt_event_ActionEvent evt)

int n = JOptionPane.showConfirmDialog(null, "Would you like an egg?",


"Order System", JOptionPane.YES_NO_OPTION);

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.

Tip. The naming convention will start with chk.


Exercise.
Step 1. Create a JFrame form and name it CheckBoxExample. Design the form as shown below.

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.

Note. It should be added in ButtonGroup to select one radio button only.

Tip. The naming convention will start with opt.


Example
Step 1. Create a JFrame and name it OptionSample. Design the form as shown below.

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.

Commonly used Methods:

Methods Description

Void It is used to add a listener to the list, to be


addListSelectionListener(ListSelectionListener notified each time a change to the
listener) selection occurs.
int getSelectedIndex() It is used to return the smallest selected cell
index.

ListModel getModel() It is used to return the data model that holds


a list of items displayed by the JList
component.
void setListData(Object[] listData) It is used to create a read-only ListModel
from an array of objects.

Tip. The naming convention will start with lst.


Example.
Step 1. Create a JFrame and name it ListExample. Design the form as shown below.

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.

Step 5. Put the code on each buttons as shown below.


Explanation
 Add() – method to add items in the list
 clear() – method to erase/delete all the items of the list
 System.exit(0) – exit the JFrame application
 Remove – method to remove/delete a specific items in the list
Step 6. Run the JFrame program. You can now add, remove, clear items on the list as well as exit
the program.

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.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

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.

void It is used to add the ActionListener.


addActionListener(ActionListener a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Tip. For the naming convention, we will start with cbo.

Example
Step 1. Create a JFrame and name it Country. Design the form as shown below.

Note. as naming convention, rename the Combo Box component to cboCountry.


Step 2. Let’s modify the items in the Combo Box. Click the combo box. In the properties
window, choose model and click the three dots (ellipsis) in red box as shown in in the
screenshot below.
Step 3. In the model window, type the data in red box as shown in the screenshot 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.

It doesn't have title bar.

Tip. The naming convention will start with pnl.


Example.
Step 1. Create a JFrame and name it SamplePanel. In the JFrame, put two Panel swing
container, each of them contains two buttons. See screenshot below

In order to put the border on the panel, you need to modify its border properties as shown below.

Do the same with panel 2.

Step 2. In each of the buttons, add the code as shown


below. Note. by now, you should be familiar with the naming
conventions.
Step 3. Run the JFrame program. You can now see that we have group two components
using panel as container.

Java JTabbedPane

The JTabbedPane class is used to switch between a group of components by clicking on a


tab with a given title or icon. It inherits JComponent class.

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.

Note. username is abc, password is 123

 $.10 each for fewer than 20 checks


 $.08 each for 20-39 checks
 $.06 each for 40-59 checks
 $.04 each for 60 or more checks

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.

Movie details below.


Movies Rating Price Time
Lord of the Rings PG 500 1300
Mission Impossible G 400 1500
John Wick R 300 1700
Jason Bourne PG-13 200 1900

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.

You might also like