You are on page 1of 131

UNIT 1: ORIENTED PROGRAMMING

Unit Objectives:

At the end of the topic session, the students should be able to:
1. recognize the benefits of OOP approach;
2. describe the basic techniques of program design in OOP;
3. cite examples of OOP concepts;
4. discuss the characteristics and application of each type of user
interface; and
5. design a graphical user interface to represent input and output of
requirements.

Think of an object that has the same shape with the given figures above. Explain the
characteristics of the object you mention and how does it affect the other objects.

The world around us is made up of objects, such as the ones you have mentioned.
Each of these objects have the ability to perform certain actions, and each action can
affect some of the other objects in the world.

Object-oriented programming is a programming methodology that defines objects


whose behaviors and interactions accomplish a given task. An object in a program
specifically software object might represent either a real-world object or an
abstraction. An object has characteristics or attributes. Just like the characteristics
of the objects you have mentioned, attributes are what the objects possess or have.
Lesson
1 Object Oriented in JAVA

A. What is Object-Oriented Programming?


 A type of programming paradigm in which programmers can define key
programming concepts, such as, data structures and the types of operations that
can be applied to them.
 Concepts can be in the form of classes, statements, and methods that can be
directly applied objects created for various purposes.
 It can also create a system comprises of programs run by modules and sub-
modules.

For example, a car has attributes such as name, current speed, and its fuel level. The
values of an object’s attributes give the object a state. The actions that an object can
take are called behaviors. Each behavior is defined by a piece of Java code called a
method.

Objects of the same kind are said to have the same data type and belong to the same
class. A class defines a kind of object; it is a blueprint for defining the objects. The
data type of an object is the name of its class.

B. What are the advantages of OOP?


 It provides a clear structure for programs. Programs can be segregated to
modules depending on the role of each section of the program.
 It makes it easy to maintain and modify existing code. New objects can be
modified by the existing ones and can be recreated.
 It allows a solid framework for code libraries. Frameworks will have no trouble
adapting to given components because they can be easily modified by the
programmer to suit specific needs.
OBJECT-ORIENTED PROGRAM

OBJECTS CLASSES

Attributes Methods

Figure1. Visual Representation of OOP

C. What is an object?
 Represents entities or data
 Can be represented using a variable in a program
D. Primary components of objects
 Attributes are the characteristics that define an object and its inherent or
initialized value.
 Methods are blocks of program code that are similar to a program’s
procedures.
E. What is a class?
 A group or collection of objects having similar or common properties
 Its inherent properties define what type of an object is created

Classes can be organized. One way of organizing classes is through inheritance.


You can define common attributes and behaviors once and have them apply to a
whole collection of specialized classes that add to or revise the details of the general
class. Inheritance enables the programmer to avoid the repetition of programming
instructions for each class.
F. What is an interface?

An interface is a program component that contains the headings for a number of


public methods. Some interfaces describe all the public methods in a class while
others specify only certain methods. An interface can also define public named
constants. In addition, an interface should include comments that describe the
methods. This is for the programmer to know the necessary information to implement
them. How the interface is used will be shown in the succeeding topics.

G. What is a package?

A package is simply a collection of related classes and interfaces that have been
grouped together into a folder. The name of the folder is the name of the package.
The classes in the package are each placed in a separate file and the file name begins
with the name of the class.

package package_name;
package java.util;

Note that the Package_Name typically consists of all lowercase letters, often
punctuated with the dot symbol.

You can use all the classes that are in a package within any program or class
definition by placing an import statement that names the package at the start of the
file containing the program or class definition. The program or class need not to be in
the same folder as the classes in the package.

import package_name.class_name_or_asterisk;
import java.util.Scanner;
import java.util.*;
Writing a class name imports just a single class from the package; writing an * imports
all the classes in the package.

WrittenAssessment
Written Assessment

Direction: Answer the Word Puzzle by encircling the programming-related words and
describe each term.
KEY ANSWERS:
Direction: Answer the Word Puzzle by encircling the programming-related words and
describe each term.

1. PROGRAM 6. PACKAGE
2. OBJECT 7. INTERFACE
3. CLASS 8. LOOP
4. METHOD 9. VARIABLE
5. INHERITANCE 10. CONDITION
Lesson
2 Object Oriented Concepts

Programmers are also inventors. We invent classes, objects, variables, methods, and
the flow of the program itself. We organize our thoughts and come up with the best
solution to a problem.

OOP concepts in Java are the main ideas behind Java’s Object-Oriented
Programming. They are an abstraction, encapsulation, inheritance, and
polymorphism. Grasping them is the key to understand how Java works. Basically,
Java OOP concepts let us create working methods and variables, then re-uses all or
part of them without compromising security.

You already know from the previous course you had how to write classes with
instance variables and methods. If you are to create two classes and the second
class has instance variables and methods just like the first one, you can derive
your new class from your existing class. In doing this, you can reuse the fields and
methods of the existing class.

1. What is abstraction? (Play Video-Abstraction “Car Models”)


 A concept that represents an object’s essential features while hiding its
unessential ones
 Simplifies systems by creating classes appropriate only to the problem
 Closely related to encapsulation and information hiding
2. What is encapsulation? (Play Video-Encapsulation “Making Medicine”)
 The ability to hide the details of an object’s internal implementations from the
users of the object
 Hides data and methods within an object while calling only the required data
and methods for a specific task
 Protects an object’s code and data from corruption or misuse Gives
maintainability, flexibility, and extensibility to code
3. What is inheritance? (Play Video-Inheritance “Chameleon”)
 The process by which objects can acquire the properties of other objects
 Provides reusability of code by adding features to an existing class without
actually modifying it

Methods of implementing inheritance in OOP:

A. Using extends keyword


Example:
Class Student assumes/ inherits the properties and methods of Class
Person
B. Using super keyword

 super ();
 super (parameter list);
 super.parameter = [parameter_value];

(1) Example:

The class initializes superclass Person attributes name and address


from class Student.

(2) Example:
Class Student refers to Person superclass attributes name and
address.
C. Method Overriding
Example:

Subclass Person2 overrides main class Person1

D. The final class

public final class className{ }


4. What is Polymorphism?
 The ability of a program to process objects differently
 Allows objects to redefine its methods for their derived classes
Example:
Subclass Person2 overrides main class Person1
Written Assessment

Direction: Answer the Word Puzzle by encircling the programming-related words and
describe each term.
3
Lesson User Interfaces

Figure2. Sample User Interface of Windows 8

People interact with computer programs through the use of its interface. The program
interface provides controls and elements that allow users to input data and the
program to display the required information.

The user interface components make a program easier and fun to use. Examples of
UI components are buttons, text fields, or any component that allows user to interact
with the program.

An interface is a program component that contains the headings for a number of


public methods. It is also an interaction between a user and a computer program. It
is an easy- to-use interface which enables the user to learn how to use the program
quickly and efficiently.
Types of User Interface

1. Graphical User Interface (GUI)


 a type of interface between a user and a computer system that involves the use of
a cursor. The cursor is used to select options from menus, make choices with
buttons, or other graphical components.

2. Command Line Interface


 a type of user that relies on textual input and output. The display screen shows
only characters and no images. Input is entirely with a keyboard. It is a text interface
that performs a specific task.
3. Touch User Interface
 a user interface that uses a touchpad or touchscreen. It is used as a combination
of an input and output device.

JAVA GUIs

Nowadays, most program interfaces contain graphical elements. The basic


constructing GUIs in JAVA Programs are Abstract Window Toolkit and Swing. In
Java, both AWT and Swing are parts of Java Foundation Classes – JFC is the
graphical framework for building and implementing graphical user interfaces. The
components created from the classes in AWT did not have a consistent appearance
when used with different browsers and operating systems that is why Swing was
created. Swing components have the prefix J to distinguish them from the original
ones (Frame for AWT, JFrame for Swing).
Abstract Window Toolkit (AWT)

The Abstract Window Toolkit is a part of Java Foundation Classes that provide
classes for designing GUI in a Java Program. It provides basic set of interfaces that
allows for displaying images, drawing texts and shapes, choosing fonts, and
manipulating colors. It has features like:

a) native user interface components


b) robust event-handling model
c) graphics and imaging tools. including shape, color, and font classes
d) the use of layout managers, for flexible window layouts that do not depend on
a particular window size or screen resolution

Example:
SYNTAX

import awt package

containers

components
and
properties
panel adds
to
components

frame adds
to
components

FileName. ProgramUsingAWT

Here is the output:

Output for ProgramUsingAWT

AWT Components
Components of AWT are considered heavyweight, because the implementation of
these components rely heavily on the underlying operating system. The
appearance of the interface is based look and feel of the particular OS and may vary
from one system to another.

AWT is included in the java.awt package and contains different components that can
be used in designing a program interface.

1. Container
The Container is a component in AWT that can contain other components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
2. Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.

3. Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.

4. Frame
The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.

5. Label
The Label component displays a single line of static text.

6. Button
The Button lets the user signal the need to perform an action.

7. Checkbox
The Checkbox is used to record a true or false state.

8. List
The List component allows the user to make one or multiple selections.

9. Choice
The Choice is used to provide a pop-up or pull-down list that allows the user to
select one at a time.
10. TextArea
The TextArea component is used for multiline input.

11. Scrollbar
The Scrollbar is used to read a value from a slider setting. It can be vertical or
horizontal.

12. Canvas
It is a type of component that provides a rectangular area where other components
can be organized by layout manager.

Swing

Swing is a part of JFC that contains classes used for creating GUI in Java. The
components created from the classes in AWT did not have a consistent
appearance when used with different browsers and operating systems that is
why Swing was created. Swing components have the prefix J to distinguish them
from the original ones (Frame for AWT, JFrame for Swing). It offers new
components and implements a concept known as “pluggable look and feel”.
Its concept makes it possible to design GUI that adapts its look and feel to its
specific platform. Swing components are 100% Java and considered
lightweight because its implementation does not rely on the underlying
operating system.

The Swing components is likely the same with the AWT; you just have to add the
letter “J” in every declaration.
SYNTAX

FileName2.

FileName.ProgramUsingSWING
Here is the output:

Output for ProgramUsingAWT

A Swing construction is usually done with the use of containers. It is a component


used to hold one or more components. It is also used to organize components into
meaningful groups.

Also, components are positioned inside the container through the use of a particular
layout manager. A layout manager is a set of classes used to organize components
in the interface. Each container has a particular layout manager associated with it.
These classes define how components will be displayed at a specific location in the
container and determine the size of each component place in the container.
Written Assessment

Direction: Write the word TRUE if the statement is correct; otherwise, write the word
FALSE.

___________1. FlowLayout is a layout manager which creates a group of


components that have equal size, displaying them in requested number of
rows and columns.

___________2. Components are contained in a container.

___________3. Swing is a part of JFC that contains classes for creating

GUI in Java and offers new components and implements a concept known as
“pluggable look and feel”.

___________4. TextArea component is used to display part of an area that is


too large for the available display area.

___________5. GridBagLayout arranges the components from left to right,


starting new rows if needed.

___________6. A container is one that can hold other graphical objects or


components.

___________7. AWT stands for Abstract Windowing Toolkit.

___________8. Java Foundation Classes is a graphical framework for building


and implements graphical user interfaces.

___________9. Swing is contained in the java.awt. package.

___________10. Graphical User Interface or GUI is a type of user interface


that allows people to communicate with computer.
Lesson
4 Swing Containers

UI components are also known as controls or widgets. To use the Swing components,
write the statement import javax.swing.*; at the beginning of your Java program. The
Swing components are usually placed in containers.

A container is a type of component that holds other components; this groups them
into a single entity.

Types of Swing Container

JWindow
It is a container that can be displayed anywhere on the user’s desktop.
The container created by JWindow does not have a title bar or border. It
is resizable and commonly used as a splash screen. It implements the
following methods:

 pack() – method that sets the size of the window


 setSize() – method used to set the width and height of the window
 setVisible – method used to display or hide the component
depending on the Boolean value of its perimeter
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJWindow as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:

SYNTAX

FileName.UsingJWindow

5. Save the Program.


6. Build and run the program. Find out what happen to the result.
JFrame

A JFrame is used to hold other components that will be displayed in the


program. It has title, size, and its visibility can be configured.

The JFrame class has four (4) constructors. These are:

1) JFrame () – creates an invisible JFrame without a title.

JFrame fr = new JFrame();

2) JFrame (String title) – constructs an invisible JFrame with a title.

JFrame fr = new JFrame(“Sample JFrame”);

3) JFrame (Graphics Configuration) – creates a JFrame in the specified


Graphics Configuration of a screen device with a blank title. The Graphics
Configuration class represents the capabilities and modes of graphics devices
such as monitor or printer.
4) JFrame (String title, Graphics Configuration) – constructs a JFrame with a
title and the specified Graphics Configuration of a screen.

Listed below are methods included in the JFrame class.

void If set to true, the JFrame is resizable


setResizable(boolean) If set to false, the JFrame is not resizable

Indicates whether the JFrame is resizable


booleanisResizable() by returning either true
or false
If set to true, the JFrame is visible If set to
void
false, the JFrame is not
setVisible(boolean)
Visible
The first two arguments set the horizontal
void setBounds(int, int, and vertical positions of the JFrame while
int, int) the final two
(2) set its width and height.

Example:
SYNTAX

FileName.UsingJFrame

Here is the output:


Once the user clicks the Close or X button in the upper-right corner, the JFrame
disappears from the screen and the program keeps running. This may not be what
every user wants. You can modify this behavior by calling the JFrame’s
setDefaultCloseOperation () method and use any of the four (4) values listed below
as an argument.

o JFrame.EXIT_ON_CLOSE – exits the program when the JFrame is closed.


o WindowConstants.DISPOSE_ON_CLOSE – closes the frame, disposes of
the JFrame object, and keeps the program running.
o WindowConstants.DO_NOTHING_ON_CLOSE – keeps the JFrame
open and running; it disables the Close button.
o WindowConstants.HIDE_ON_CLOSE – closes the JFrame and keeps the
program running.

Here is a sample code for JFrame.EXIT_ON_CLOSE.

fr. setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

fr. setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

fr. setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);

The look and feel are the default appearance and behavior of any user interface.
Java’s look and feel is known by the name Metal. The look and feel of a JFrame can
be:
SYNTAX

FileName.UsingJFrameExitOnClose

Here is the output:


JPanel
It is a container that can hold other components and is commonly placed inside
a frame. It adds and create rectangular area inside a frame; can also be put
with colors.

 setLayout(LayoutManager layout) – a method that is used to set the


layout manager for the panel.
 setPreferredSize(new Dimension(int, width, int height) – a method
that is used to set the preferred size on the component to a constant
value.
 setBackground(Color.c) – a method that is used to set the background
color of the panel.
 setSize – a method that is used to set size of width and height of the
panel.
 add(component) – a method that is used to add the components to the
panel.
Laboratory Exercise

1. Create a New Project.


2. Edit the program codes by typing the following syntax

SYNTAX

FileName.UsingPanel
3. Save the program.
4. Compare the result.
Lesson5 Text Components

Text Components are components in Swing that enable the users to view, display,
and edit text in a program. This lesson explains the functions, methods, and attributes
of classes that are used to create labels, buttons, textfields, textareas, and scrollpane.
It is simply a component for displaying texts.

JLabel

A JLabel is added to the JFrame using the “add() method”. The JLabel class
includes the following constructors:

 JLabel () – constructs a JLabel without a title and image.

JLabel lbl = new JLabel();

 JLabel (String text)– creates a JLabel with the specified text.

JLabel lbl = new JLabel(“OK”);


fr.add(lb);

Here is the output:


 JLabel (Icon image) – creates a JLabel with the specified image. Note that the
image must be in the same specified folder with the program. It’s size also remain
whatever the size you create from the JFrame.

Icon ic = new ImageIcon(“icon.jpg”);


JLabel lb = new JLabel(ic);
fr.add(lb);

Here is the output:

 JLabel (String text, int horizontal Alignment) – constructs a JLabel with the
specified text and horizontal alignments.

JLabel lb = new JLabel


(“OK”, JLabel.CENTER);
Here is the output:

 JLabel (Icon image, int horizontal Alignment) – constructs a JLabel with the specified
image and horizontal alignment.

Icon ic = new ImageIcon(“icon.png”);


JLavbel lb = new JLabel(ic, JLabel.RIGHT);
fr.add(lb);

Here is the output: (with DefaultLookAndFeelDecorated)

 JLabel (String text, Icon, int horizontal Alignment) – constructs a JLabel with the
specified text, image, and horizontal alignment.

Icon ic = new ImageIcon(“icon.png”);


JLavbel lb = new JLabel(“OK”,ic, JLabel.RIGHT);
fr.add(lb);
Here is the output: (with DefaultLookAndFeelDecorated)

The text in a JLabel can be modified using the setText () method and can be retrieved
using the getText () method. Also, the JLabel itself can be omitted from the JFrame
through the remove () method. If you add or remove a component from a container,
you have to call one of these methods: invalidate (), validate (), and repaint ().
Otherwise, the changes will not take effect. The invalidate () and validate () methods
are part of the Container class while the repaint() method is part of the Component
class.

The setFont () method of the Font class allows you to change the typeface, style, and
size of a font. The Font class is imported from the java.awt package. To create Font
object, three (3) arguments are needed:

 Typeface – represents the font face. Examples are Arial, Century, and Times New
Roman.
 Style – applies an attribute to displayed text and is one of three (3) values: Font.
PLAIN, Font. BOLD, or Font. ITALIC.
 Point Size – an integer that represents about 1/72 of an inch. A printed text is
commonly 12 points while a headline might be 30 points.
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJLabel as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

FileName.UsingJLabelWFont

34
JButton

JButton is a Swing component that implements the push button. It simply triggers
an action when the user clicks the button. It is one of the most popular graphical
components.

JButton supports an ImageIcon objects that allow icons to appear on the face of
the button. It is also a component that the user can click for data input. It is typically
partnered with a text field. The button will only display adding it inside a frame and
with the use of a panel. Shown below are the examples of codes to be added to
create a button.

There are five (5) constructors for button partnered with frame:

1. JButton () – creates a button without text.

JButton bt = new JButton ();

Here is the output:

2. JButton (String text) – constructs a button with a text display.

JButton bt = new JButton (“CLICK”);

35
Here is the output:

3. JButton (icon) – creates a button with an icon display on it; remember that
the size of the image icon you will use will be stable with the button.

Icon ic = new ImageIcon (“icon.png”);


JButton bt = new JButton(ic);

Here is the output:


Note: Use different color for JFrame and JPanel.

4. JButton (text, icon) – creates a button with an icon display and a text on
it; remember that the size of the image icon you will use will be stable with
the button. – same with the alignment of text in which the programmer will
prefer.

36
Icon ic = new ImageIcon (“icon.png”);
JButton bt = new JButton(“OK”, ic);

Here is the output:


Note: Use different color for JFrame and JPanel.

5. JButton (Action a) – creates a button in which properties are taken from


the Action (class) supplied. An Action object is created if there are two (2)
or more components that perform the same function.

37
Laboratory Exercise

1. Create a New Project.


2. Specify UsingButton as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

FileName.UsingJButton

38
JTextField

JTextField is a component that allows editing of a single line of text. It can


be used to input data and display information. A JTextField allows a user to
type a single line of text data (any characters you can enter from the
keyboard). Shown below is the hierarchy of the JTextField class.

To create a JTextField object, you can select one (1) from the following
constructors:
o JTextField () – constructs an empty JTextField

JTextField tf = new JTextField();

Here is the output:

o JTextField (int columns) – creates an empty JTextField with a


specified number of columns.

JTextField tf = new JTextField();

39
o JTextField (String Text) – constructs a new JTextfield with an initial
text display.

JTextField tf = new JTextField(“Type your name here”);

Here is the output:

o JTextField (String Text, int columns) – constructs a new JTextfield


with an initial text display and specified number of columns.

JTextField tf = new JTextField(“Type your name here”, 20);

Here is the output:

40
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJTextField as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

FileName.UsingJTextField

41
JTextArea

JTextArea is a component that displays multiple lines of text and optionally allows
the user to edit the text. Use any of the following constructors to create an instance
of JTextArea class:

o JTextArea (int rows, int columns) – specifies the number of rows and
columns that the user can input.
o JTextArea (String Text) – display an initial text with the given textfield area.
o JTextArea (String Text, int rows, int columns) - combination of the two
type of classes you can use to program the text area.

SYNTAX

42
FileName.UsingJTextArea

Here is the output:

43
JScrollPane

Swing supports scrollbars through the use of JScrollPane class. It acts as a


container that adds scrollbars to support vertical and horizontal scrolling.

When components in a user interface require more display area than they have
been allocated, a JScrollPane container can be used to hold the components in a
way that allows a user to initially invisible parts of the pane into view.

A JScrollPane provides scroll bars along the side or the bottom of a pane, or both,
with a viewable area called a viewport.

The following are the constructors for the JScrollPane.

 JScrollPane () – creates an empty JScrollPane in which both horizontal


and vertical scroll bars appear when needed.

JScrollPane sp = new JScrollPane();

 JScrollPane (Component) – creates an empty JScrollPane in that


displays the contents of the specified component.

JLabel lb = new JLabel();


JScrollPane sp = new JScrollPane();

 JScrollPane (int, int) – creates an empty JScrollPane with both vertical


and horizontal scroll bar specifications.

44
JScrollPane sp = new JScrollPane(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

 JScrollPane (Component, int) – creates a JScrollPane that displays the


specified component and includes both vertical and horizontal bar
specifications.

JScrollPane sp = new JScrollPane(lb,


JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Other Arguments in JScrollpane are:

1. JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED

2. JScrollPane.VERTICAL_SCROLLBAR_NEVER

3. JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED

4. ScrollPane.HORIZONTAL_SCROLLBAR_AS_ALWAYS

45
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJScrollPane as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

FileName.UsingJScrollPane

46
Lesson
6 Selection Components in OOP

Java Swing provides components to choose an option or multiple options. This


lesson describes the function and characteristics of the following components:
checkbox, radiobutton, list, and combo box – or also known as choice button.

 JCheckbox
The JCheckbox is a component that allows a user to select any number of check
boxes in a group. A checkbox is a small box that represents an option. Its
selection is indicated by a check mark or x-mark. It allows users to choose one
(1) or more items. It contains a label positioned before a square.

It has two states: (a) true for selected, and (b) false for deselected. Selection
can be made by clicking one or more options represented by checkboxes.

These are the frequently used JCheckBox methods:

Method Description
void setText(String)  Sets the text for the JCheckBox
String getText()  Returns the JCheckBox text
 Sets the state of the JCheckBox to true for
void
selected or false for
setSelected(boolean)
 unselected
 Gets the current state (checked or unchecked)
boolean isSelected() of the
 JCheckBox
Listed below are the constructors that can be used with the JCheckBox
class:

o JCheckBox() – creates a checkbox without a label.

o JCheckBox(String label) – creates a checkbox with a label.

o JCheckBox(String label, boolean state) – creates a


checkbox (selected or unselected) with a label.

47
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJCheckBox as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

48
FileName.UsingJCheckBox

6. Save the Program.


7. Build and run the program.

49
 JRadioButton
The JRadioButton class is used to create radio button components. A radio
button is a small circle component that represents an option. It is indicated
by a small dot at the center of the circle. It has two states: (a) true for
selected, and (b) for false and deselected. Selection can be made by
clicking one of the options represented by radio buttons.

These are the frequently used JRadioButton methods:

Method Description
 a method that is used to add a radio button
add(radiobutton)
to the group
 a method that returns the selected option
getSelectedJRadioButton()
on the group
setSelectedJRadioButton  a method that is used to set the status of a
(radiobutton) particular radio button

Listed below are the constructors that can be used with the JRadioButton class:

o JRadioButton rb – creates a radiobutton without a label.

o JRadioButton (String label) – creates a radiobutton with a label.

o JRadioButton(String label, boolean state) – creates a radiobutton


(selected or unselected) with a label.

50
Laboratory Exercise

1. Create a New Project.


2. Specify UsingRadioButton as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

51
FileName.UsingJRadioButton

6. Save the Program.


7. Build and run the program. Compare the result from the illustration below.

52
 JList
JList is a class that is used to create list box from which one or more options
can be displayed with data (commonly data from an array). It is placed inside
the scrollpane in order to display the items on the list.

These are the frequently used JList methods:

Method Description
 a method that is used to register the
addListSelectionListener
component in order to be monitored by the
(action-listener)
ListSelectionListener
 a method that is used to set selection to an
setSelectedIndex(int index)
item on the list
 a method that is used to set array
setListData(listData)
containing the list of data
 a method used to specify the preferred
setVisibleRowCount
number of rows in the list that will display
(int visibleRowCounter)
without the scrollbar
 a method that is used to set whether the
setSelectionMode
component allows single-item or multiple-
(selectionMode)
item selection
 a method that returns the first selected item
getSelectedValue() on the list or null when no item is the list is
selected
 a method that returns the index of the first
getSelectedIndex() selected item on the list or -1 when no item
is selected in the list
 a method that returns the data model
getModel()
holding the list of items displayed on the
getSelectionMode()
component

53
Listed below are the constructors that can be used with the JList class:

o JList list – creates a list with an empty model.

o JList (String label) – creates a list that displays a set of specified


components in a non-null model
o JList (Object [ ] listData) – creates a list that displays the elements of an
array.

The JList is characterizes with selection mode values: (a) Single Selection
– when only one item is to be selected, (b) Single Interval Selection – is
used when one contiguous item can be selected at a time, (c) Multiple
Interval Selection – is the default type of set selection mode that allows
non-contiguous items can be selected at a time.

54
Laboratory Exercise

1. Create a New Project.


2. Specify UsingJList as the file name.
3. Make sure to specify the folder location.
4. Edit the program codes by typing the following syntax:
5. Find out the result.

SYNTAX

55
FileName.UsingJList

6. Save the Program.


7. Build and run the program. Compare the result from the illustration below.

56
 JComboBox
A combo box is a class used to create a combo box component. A combo box
contains a drop-down list box that displays a list of options and allows selections
to be made on one or more options. There are two types of combo box: editable
and uneditable combo boxes. Before you create an array of strings that will be
passed to the combo box. You can also use objects other than strings; but string
is the most commonly used objects.

A JComBox is a component that combines two (2) features: a display area


showing a default option and a list box that contains additional, alternate
options.

When a JComboBox appears on the screen, the default option is displayed.


When the user clicks the JComboBox, a list of alternative items dropdown;
if the user selects one, it replaces the box’s displayed item.

To add items in a JComboBox, you can use the addItem() method.

57
FileName.UsingJComboBox

Here is the output:

58
Lesson7 Menus and Toolbars

Menu bar and toolbar are components of Java that are used to group the
components to perform a specific task. Menu bar is part of application interface
where drop down menus are displayed. It is commonly used to access specific
menus.

Toolbars are designed to directly select components on the toolbars to accomplish


the task instead of searching for a command option in the menu bar.

JToolBar is a component that contains several components that are usually


buttons and separators. The purpose of JToolbar is to group the related
components within the object.

Creating Menus

Swing provides a set of classes to support the creation of popup and pull-
down menus. The sets contain are:

 JMenuBar – is a container that holds one or more JMenu


Components. It is commonly placed at the top of the frame
right below the frame title bar.

JMenuBar mbName = new JMenuBar();

 JMenu – is a container that holds JMenuItem components.


These items are being grouped together based on relation.

JMenu mnuName = new JMenu(); ||


JMenu mnuName = new JMenu(String);

59
Methods used are:
1. add(item) – use to add item on the menu
2. addSeparator () – use to add a line to separate the item
from one another
3. setEnabled – use to enable or disable an item menu
Example:

60
FileName.UsingJMenus

Build and run the program. The output must be:

61
When you hover the mouse to each item, this is what’s going to happen:

62
Adding a Toolbar

JToolbar is a component containing several components that are usually


buttons and separators. The purpose of JToolbar is to group related
components within the toolbar. It can be placed either horizontally or
vertically on the frame. There are two types of toolbars: (a) dockable and
(b)floatable toolbars.

A dockable toolbar snaps a portion of the frame when it is moved and


requires a BorderLayout as its layout manager.

A floatable toolbar on the other hand, is displayed on the frame without


snapping to any portion of the frame.

Methods used are:


1. add(component) – use to add number of components
on the toolbar
2. addSeparator () – use to add a line to separate the
component from one another
3. setFloatable(boolean) – use to enable or disable the
floatable bar
Example:

63
FileName.UsingJToolBar

Here is the output:


Note: The image icons must be in .gif format to enable a compatible display in the
web, and must be located together with the program file.

64
Pointers to Keep in Mind

Object-oriented programming is a programming methodology that defines


objects whose behaviors and interactions accomplish a given task.
Attributes are the characteristics that an object possess.
Object-oriented concepts can be in the form of classes, statements, and
methods that can be directly applied objects created for various purposes.
Programs run by modules and sub-modules.
A class defines a kind of object; it is a blueprint for defining the objects.
The data type of an object is the name of its class.
OOP in Java provides a clear structure for programs, maintain and modify
existing code and allows a solid framework for code libraries.
An object represents any data and can be represented by a variable.
The primary components of an object are classes and methods.
An interface is a program component that contains the headings for a number
of public methods.
A package is simply a collection of related classes and interfaces that have
been grouped together into a folder.

Abstraction is a concept that represents an object’s essential features while


hiding its unessential ones.
Encapsulation is the ability to hide the details of an object’s internal
implementations from the users of the object.
Inheritance is the process by which objects can acquire the properties of other
objects.
Methods of implementing inheritance in OOP includes:
o Using extends keyword
o Using super keyword

65
o Method Overriding
o The final class
Polymorphism is the ability of a program to process objects differently.

The user interface components make a program easier and fun to use. Examples
of UI components are buttons, text fields, or any component that allows user to
interact with the program.

AWT and SWING Packages


Swing Components are: components, containers, and layout
Containers are: JWindow, JFrame, and JPanel
Text Components are: JLabel, JTextField, JTextArea
Some layouts are: JButton & JScrollPane
Choice/ Selection Components include: JCheckbox, JRadioButton,
JList, and JComboBox.
Classes use to create menus are: JMenu and JToolBar

66
UNIT 2: GRAPHICAL USER INTERFACE – LAYOUTS

Unit Objectives:

At the end of the topic session, the students should be able to:

6. understand the different layouts in designing object-oriented


programming outputs;
7. use the most suitable layout manager in order to design a user-
friendly GUI;
8. cite examples of layouts and multiple layouts; and
9. design a graphical user interface to represent the input and
output requirements of the given problem.

Ask the students which among the window is more pleasing in the eye and
catchier? After that, let them justify their answers.

Although two (2) JLabels are added to the JFrame, only the second one is visible.
This is what happens when a JFrame does not have a layout manager. The
design differs based on how it is being created by the programmer. Most of the
advertising company prefer the layout windows while the other normally prefer
the simple one.

67
Lesson
1 Layout Manager

In the previous unit, you have learned how to implement different Swing
components in a Java program. you also learned how to utilize the objects
available in the Java language. By default, these containers and objects are
arranged from left to right of a particular container. Adding a new component to a
container will automatically resize the container. Moving and resizing the container
rearranges the position of the components in the container.

Using the default rearrangement of components makes the program interface


difficult to use and disorganize to the eye of the user. In addition to default
arrangement of containers and objects in Java, it provides additional tools for
organizing the components in the container. These tools are collectively known as
the layout manager.

A layout manager controls the positioning of the components. Layout managers


are from the java.awt package. If you want all your components to be visible, use
a flow layout manager; create a FlowLayout object. This places components in a
row and when a row is filled, components are automatically placed into the next
row.

But remember to know the normal part of the JFrame to be able to quickly put
objects and components simultaneously to the frame itself before putting a layout
to it. The figure below shows the original position of its component or parts of
JFrame.

68
What is Layout Manager?
A layout manager is an object that implements the Layout Manager interface
and determines the size and position of the components within a container.
Although components can provide size and alignment hints, a container's
layout manager has the final say on the size and position of the components
within the container.

The default layout manager is the FlowLayout. Components in this layout


are arranged from left to right of the container. Other types of layout manager
will be discussed to this section. The objects and classes associated with
layout managers are contained in the java.awt package.

How to set the layout manager?


As a rule, the only containers whose layout managers you need to worry
about are JPanels and content panes. Each JPanel object is initialized to use
a FlowLayout, unless you specify differently when creating the JPanel.
Content panes use BorderLayout by default. If you do not like the default
layout manager that a panel or content pane uses, you are free to change it
to a different one. However, unless you are using JToolBar,
the FlowLayout and BorderLayout managers are only useful for prototyping.
Any real application will need to reset the layout manager. Again, you should
use an appropriate tool to do this, rather than coding the manager by hand.

69
FlowLayout

FlowLayout manager, which positions components in rows from left to right across
their container. Each component you place within a Container can also be a
Container itself, so layout managers can be assigned within layout managers.

The FlowLayout class provides a very simple layout manager that is used, by
default, by the JPanel objects. The following figure represents a snapshot of an
application that uses the flow layout:

Here is the sample code:

SYNTAX

70
FileName.LayoutM-FlowLayout

This will appear upon running the application:

If you resize the window, this will happen:

71
BorderLayout

This layout adds components to a maximum of five (5) sections arranged in


north, south, east, west, and center positions. If the window is enlarged, the
center area gets as much of the available space as possible. The other areas
expand only as much as necessary to fill all available space. Often a container
uses only one or two of the areas of the BorderLayout object — just the center,
or the center and the bottom.

SYNTAX

72
FileName.LayoutMBorderLayout

The result must be:

Note: Resizing the window won’t affect the positioning of its content in the
container.

73
GridLayout

The GridLayout is a type of layout manager that arranges the components into a
rectangular grid. The container is divided into a specified number of columns and
rows. The components are arranged from left to right and top to bottom. The size
of each component corresponds to the area occupied by the cell within the grid.

The constructor of the GridLayout class creates an instance that has two columns
and as many rows as necessary.

The program illustrates how to organize the interface through the user of buttons
in layout manager.

SYNTAX

74
FileName.LayoutMGridLayout

If your run the program the output must be:

75
Laboratory Exercise

6. Create a New Project.


7. Specify UsingGridLayout as the file name.
8. Make sure to specify the folder location.
9. Edit the program codes by typing the following syntax:
10. Find out the result.

SYNTAX

76
FileName.UsingGridLayout

11. Save the Program.


12. Run and discuss the result.

77
GridBagLayout

This layout manager sets size, placement, and alignment constraints for every
component that you add. GridBagLayout is one of the most flexible — and complex
— layout managers the Java platform provides. A GridBagLayout places
components in a grid of rows and columns, allowing specified components to span
multiple rows or columns. Not all rows necessarily have the same height. Similarly,
not all columns necessarily have the same width. Essentially, GridBagLayout places
components in rectangles (cells) in a grid, and then uses the components'
preferred sizes to determine how big the cells should be.

The following figure shows the grid for the preceding applet. As you can see, the
grid has three rows and three columns. The button in the second row spans all the
columns; the button in the third row spans the two right columns.

If you enlarge the window as shown in the following figure, you will notice that the
bottom row, which contains Button 5, gets all the new vertical space. The new
horizontal space is split evenly among all the columns. This resizing behavior is
based on weights the program assigns to individual components in
the GridBagLayout. You will also notice that each component takes up all the
available horizontal space — but not (as you can see with button 5) all the available
vertical space. This behavior is also specified by the program.

78
This behavior is also specified by the program.

The way the program specifies the size and position characteristics of its
components is by specifying constraints for each component. The preferred
approach to set constraints on a component is to use the Container.add variant,
passing it a GridBagConstraints object.

How to Specify the GridBagConstraints?

You can set the following GridBagConstraints instance variables:

 gridx, gridy

Specify the row and column at the upper left of the component. The
leftmost column has address gridx=0 and the top row has
address gridy=0. Use GridBagConstraints.RELATIVE (the default
value) to specify that the component be placed just to the right of
(for gridx) or just below (for gridy) the component that was added to the
container just before this component was added. We recommend
specifying the gridx and gridy values for each component rather than
just using GridBagConstraints.RELATIVE; this tends to result in more
predictable layouts.

79
 gridwidth, gridheight

Specify the number of columns (for gridwidth) or rows (for gridheight) in


the component's display area. These constraints specify the number of
cells the component uses, not the number of pixels it uses. The default
value is 1. Use GridBagConstraints.REMAINDER to specify that the
component be the last one in its row (for gridwidth) or column
(for gridheight). Use GridBagConstraints.RELATIVE to specify that the
component be the next to last one in its row (for gridwidth) or column
(for gridheight). We recommend the specification of
the gridwidth and gridheight values for each component rather than just
using GridBagConstraints.RELATIVE and GridBagConstraints.REMAIN
DER; this tends to result in more predictable layouts.

Note: GridBagLayout does not allow components to span multiple


rows unless the component is in the leftmost column or you have
specified positive gridx and gridy values for the component.

 fill

Used when the component's display area is larger than the component's
requested size to determine whether and how to resize the component.
Valid values (defined as GridBagConstraints constants) include NONE (the
default), HORIZONTAL (make the component wide enough to fill its display
area horizontally, but do not change its height), VERTICAL (make the
component tall enough to fill its display area vertically, but do not change its
width), and BOTH (make the component fill its display area entirely).

 ipadx, ipady

Specifies the internal padding: how much to add to the size of the
component. The default value is zero. The width of the component will be
at least its minimum width plus ipadx*2 pixels, since the padding applies to
both sides of the component. Similarly, the height of the component will be
at least its minimum height plus ipady*2 pixels.

80
 insets

Specifies the external padding of the component -- the minimum amount of


space between the component and the edges of its display area. The value
is specified as an Insets object. By default, each component has no external
padding.

 anchor

Used when the component is smaller than its display area to determine
where (within the area) to place the component. Valid values (defined
as GridBagConstraints constants) are:

a) CENTER (the default)


b) PAGE_START
c) PAGE_END
d) LINE_START
e) LINE_END
f) FIRST_LINE_START
g) FIRST_LINE_END
h) LAST_LINE_END
i) LAST_LINE_START

81
Laboratory Exercise

1. Create a New Project.


2. Specify UsingGridBagLayout_P2 as the file name.
3. Make sure to specify the folder location.
4. Using the GridBagLayout Manager, design a program interface that will produce
the given output:

82
BoxLayout

The Swing packages include a general purpose layout manager


named BoxLayout. BoxLayout either stacks its components on top of each other
or places them in a row — your choice. You might think of it as a version
of FlowLayout, but with greater functionality. Here is a picture of an application that
demonstrates using BoxLayout to display a centered column of components:

The BoxLayout is a type of layout manager that is similar to the FlowLayout


manager. Each component occupies the height of the container and is arranged
from left to right. Unlike the FlowLayout manager which is only limited to horizontal
arrangement, the BoxLayout manager allows the components from the container
to be arranged either horizontally or vertically.

83
Here is an example:

SYNTAX

FileName.UsingBoxLayout

84
The output of the program must be:

85
Laboratory Exercise

1. Create a New Project.


2. Specify UsingBoxLayout as the file name.
3. Make sure to specify the folder location.
4. Using the GridBagLayout Manager, design a program interface that will produce
the given output:
Note: This is when the JCheckBox is checked by default.

Note: This is when the JCheckBox is unchecked. Clue is by using a


conditional statement.

86
Lesson
2 Multiple Layout Managers

Creating a program interface in Java requires the selection of the appropriate


layout manager and organizing components within a container. At first, organizing
and designing the interface is a little bit challenging; but with thorough practice, a
user-friendly interface can be attained. By default, each container requires a layout
manager to be implemented; however, there are times that the components can
be organized more effectively if more than one type of layout manager is
implemented in the program.

This topic discusses the techniques on how to


organize the program interfaces through the use of
more than one layout manager. This topic will also
illustrate the function of the CardLayout manager.

We knew from the previous lesson that, layout


manager in Java is responsible for placing the
components such as buttons and text boxes on the
Gestalt principles in UI application. This lesson will also explain
design
how layout manager object is being well utilized to
determine size and position of components in a container.

The Importance of User Interface Design. It is important for any web designer
to design functional sites that can easily generate interest and online traffic among
the internet users. Therefore, web designers should give due importance to
the user interface of the site which is being designed by them.

87
CardLayout

The CardLayout class manages two or more components


(usually JPanel instances) that share the same display space. When using
the CardLayout class, let the user choose between the components by using a
combo box. The CardLayoutDemo application is an example to illustrate this
feature.

It is a type of layout manager that is used to organize a group of containers. It


treats every component in the container as a card. One card is displayed at a time
and the container acts as a stack of card. This type of layout manager differs from
other layout manager because it hides some components from the screen. The
common approach to use a card layout is to use a panel for each card.

Another way to accomplish the same task is to use a tabbed pane. The following
picture shows a tabbed pane version of the preceding example:

Because a tabbed pane provides its own GUI, using a tabbed pane is simpler than
using the CardLayout class. For example, implementing the preceding example
using a tabbed pane results in a program with fewer lines of code.

88
Here is an example:

SYNTAX

89
FileName.UsingCardLayout

If you save and run the program, the result must be:

90
Laboratory Exercise

1. Create a New Project.


2. Specify UsingBoxLayout as the file name.
3. Make sure to specify the folder location.
4. Using the CardLayout Manager, design a program interface that will produce
the given output:

Note: This is by default when you run the system.

Note: This is by default when you click the use of JTextField:

91
Pointers to Keep in Mind

A layout manager controls the positioning of the components. Layout


managers are from the java.awt package. If you want all your components
to be visible, use a flow layout manager; create a FlowLayout object. This
places components in a row and when a row is filled, components are
automatically placed into the next row.
The layout manager is used to organize components in the container.
Different Types of Layout Manager includes:
 BorderLayout
 GridLayout
 BoxLayout
 CardLayout
 GridBagLayout

92
UNIT 3: OOP EVENT HANDLING & LISTENERS

Unit Objectives:

At the end of the topic session, the students should be able to:

10. understand the concepts events, listeners, and interfaces;


11. describe the event handling processes;
12. design a graphical user interface to represent the input and
output requirements of the problem;
13. determine the possible sources of events; and
14. add functionality to the GUI by implementing the most suitable
listeners.

This lesson gives you details about writing event listeners. You might not need to
read this section. Your first source of information for event should be the how-to
section for the component in question. Each component's section shows code for
handling the events most commonly needed when implementing the component.

93
Lesson
1 Events in Java

In the previous unit, you have learned how to create and design a program
interface through the use of different components, containers, and layout
managers. The next step is to make the program interface respond to user or
computer actions. In Java, these actions are identified as events.

What is Event Handling?

This section discusses several design considerations to keep in mind when


implementing event handlers in your application. We then introduce you to event
objects small objects that describe each event. In particular, we talk
about EventObject, the superclass for all AWT and Swing events. Next, we
introduce the concepts of low-level events and semantic events, recommending
that you prefer semantic events when possible. The remainder of this section
discusses implementation techniques you might use in some event listeners or see
in event listeners created by other people or by GUI builders.

Event handling is the mechanism that controls the event and decides what
should happen when an event occurs.
An event is a mechanism, by which components inform the program that an
action has occurred. An event can be a mouse action or keyboard entry. On Java,
events are implemented through the use of the classes in the java.awt event
package. Programming a component to respond to a particular event involves the
use of the following element:

EVENT SOURCE EVENT LISTENER EVENT LISTENER

the GUI component that a set of program codes a method that the
can generate an event which awaits and listener will invoke
to an object registers that an event or implement when
has occurred an event occurred

94
What are the common events?
There are numerous event classes that can be implemented in Java
Programs; however, this unit focuses only on numerous events. Each event
class has a listener interface associated with it. A listener represents the
interface responsible to handle the event. Every listener has a handler that
is responsible for dealing with certain events. Listed below are common user
actions and the events that are generated from them.

User Action Resulting Event Type

Click a button ActionEvent


Click a component MouseEvent
Click an item in a list box or
in a ItemEvent
checkbox
Change text in a text field TextEvent
Open or iconify a window WindowEvent
Press a key KeyEvent

Action Event
Components such as the Button and JButton fire off ActionEvents to
indicate some kind of component-defined action. For example,
the Button fires off an ActionEvent whenever the user presses it. The entire
point of an event is to inform a listener that something has happened to a
component in the GUI. An event includes all of the information that a listener
needs to figure out what happened and to whom it happened (the what and
who of the event). An event must give enough information to fully describe
itself. That way, a listener can figure out what exactly happened and
respond in a meaningful way.

95
a) The ActionEvent includes methods for learning the action's
command string, modifiers, and identification string.
b) The getActionCommand() method returns the command string that
indicates the event's intended action, such as print or copy (the
what).
c) The getSource() method returns the object that generates the event
(the who).

In order to receive an ActionEvent, a listener must implement


the ActionListener interface and register itself with the component.
Furthermore, a component must keep track of its listeners in order to notify
them of an event.

Focus Event
Focus events are generated when a component gets or loses input focus.
Focus events come in two flavors, permanent and temporary. Permanent
focus events occur with explicit focus changes. For example, when the
user tabs through components, this causes permanent focus events. An
example of a temporary focus event is when a component loses focus as
its containing window is deactivated.

The constants of a FocusEvent are as follows:

 FOCUS_FIRST
Specifies the beginning range of focus event ID values.

SYNTAX

public final static int FOCUS_FIRST

96
 FOCUS_GAINED
Event type ID indicating that the component gained the input focus.

SYNTAX

public final static int FOCUS_GAINED

 FOCUS_LAST
Specifies the ending range of focus event ID values.

SYNTAX

public final static int FOCUS_LAST

 FOCUS_LOST
Event type ID indicating that the component lost the input focus.

SYNTAX

public final static int FOCUS_LOST

97
Item Event
An item event is an event that occurs when a user selects an item for a list.
The components associated with this event are: JButton, JCheckbox,
JComboBox, and JRadioButton. The commonly used methods are:

getSource() a method that identifies the object from which the


ItemEvent is originated.
the method that is used to examine which
getItemSelectable() component was clicked by the user
the method which returns value that indicates
getStateChanged() whether or not the state of the components have
changed.

Key Event
It is a type of event that occurs when a component receives an input from
the keyboard. This event is triggered and generated by the component
(such as textfield) when a key is pressed, released, OR TYPED. This
generated the event with all the components.

getKeyCode() a method that returns the keyCode. It is an


integer value that represents the key.

the method that is used to return the character


getKeyChar()
associated with the key

Mouse Event
A mouse event is generated by the following user actions: (a) pressing the
mouse, (b) releasing the mouse button, (c) moving the pointer, and (d)
hovering the mouse pointer. The following list describes the methods
associated with the mouse event.

98
getSource() a method that identifies the object from which the
MouseEvent is originated.
the method that is used to return the horizontal x
getX() position of the mouse location

the method that is used to return the horizontal y


getY() position of the mouse location

Window Event
A window event is an event that is generated when a user is activated,
deactivated, iconified, deiconified, opened, or closed a window project. The
associated components are: JFrame, JOpenDialog, and WindowDialog.

getSource() a method that identifies the object from which the


WindowsEvent is originated.
the method for WINDOW_STATE_CHANGED
getNewState() events and returns the new state window.

the method for WINDOW_STATE_CHANGED


getOldState() events and returns the previous state window.

99
100
Lesson
2 Event Listeners in Java

Event listeners represent the interfaces responsible to handle events. Java


provides various Event listener classes, however, only those which are more
frequently used will be discussed. Every method of an event listener method has
a single argument as an object which is the subclass of EventObject class. For
example, mouse event listener methods will accept instance of MouseEvent,
where MouseEvent derives from EventObject.

Action Listener

Action listeners are probably the easiest — and most common — event
handlers to implement. You implement an action listener to define what
should be done when a user performs certain operation.

An action event occurs, whenever an action is performed by the user.


Examples: When the user clicks a button, chooses a menu item, presses
Enter in a text field. The result is that an actionPerformed message is sent to
all action listeners that are registered on the relevant component.

To write an Action Listener, follow the steps given below:

1. Declare an event handler class and specify that the class either
implements an ActionListener interface or extends a class that
implements an ActionListener interface.
2. Register an instance of the event handler class as a listener on one or
more components. For example:
3. Include code that implements the methods in listener interface.
4. In general, to detect when the user clicks an onscreen button (or does
the keyboard equivalent), a program must have an object that
implements the ActionListener interface.

101
5. The program must register this object as an action listener on the
button (the event source), using the addActionListener method. When
the user clicks the onscreen button, the button fires an action event.

6. This results in the invocation of the action listener's actionPerformed


method (the only method in the ActionListener interface).

7. The single argument to the method is an ActionEvent object that gives


information about the event and its source.

This is an example:

SYNTAX

102
103
The output when you run the program must be:

Try to hoven the mouse along the colored text and see how it generates the
changes occur in the mouse moved value.

104
Focus Listener

Focus events are fired whenever a component gains or loses the keyboard
focus. This is true whether the change in focus occurs through the mouse,
the keyboard, or programmatically. To get familiar with basic focus concepts
or to obtain detailed information about focus, see How to Use the Focus
Subsystem.

This section explains how to get focus events for a particular component by
registering a FocusListener instance on it. To get focus for a window only,
implement a WindowFocusListener instance instead.

To obtain the focus status of many components, consider implementing


a PropertyChangeListener instance on the Keyboard Focus
Manager class, as described in Tracking Focus Changes to Multiple
Components in How to Use the Focus Subsystem.

The following example demonstrates focus events. The window displays a


variety of components. A focus listener, registered on each component,
reports every focus-gained and focus-lost event. For each event, the other
component involved in the focus change, the opposite component, is
reported. For example, when the focus goes from a button to a text field, a
focus-lost event is fired by the button (with the text field as the opposite
component) and then a focus-gained event is fired by the text field (with the
button as the opposite component). Focus-lost as well as focus-gained
events can be temporary. For example, a temporary focus-lost event occurs
when the window loses the focus. A temporary focus-gained event occurs on
popup menus.

The interface FocusListener is used for receiving keyboard focus events.


The class that processes focus events needs to implements this interface.

105
This is an example:

SYNTAX

106
Here is the output:

107
This is by default the result when you run the program. When you clicked “OK” this
is what’s going to happen:

108
Item Listener

The class which processes the ItemEvent should implement this interface.
The object of that class must be registered with a component. The object can
be registered using the addItemListener () method. When the action event
occurs, that object's itemStateChanged method is invoked.

SYNTAX

109
Here is the output: Now, when you select or
click a particular checkbox choice, this will
happen.

110
The program function based on how the button is being invoked by the
user itself. But you need to add extra condition if all of the checkboxes
have been checked.

111
Key Listener

The class which processes the KeyEvent should implement this interface.
The object of that class must be registered with a component. The object can
be registered using the addKeyListener () method.

Interface Methods
Sr.No. Method & Description

void keyPressed(KeyEvent e)
1
Invoked when a key has been pressed.

void keyReleased(KeyEvent e)
2
Invoked when a key has been released.

void keyTyped(KeyEvent e)
3
Invoked when a key has been typed.

SYNTAX

112
113
This is the output when you compile and run the program:

114
When you typed any characters or numbers in the textfield, it will result to this:

115
Mouse Listener

The class which processes the MouseEvent should implement this interface.
The object of that class must be registered with a component. The object can
be registered using the addMouseListener () method.

Interface Methods

Sr.No. Method & Description

void mouseClicked(MouseEvent e)
1
Invoked when the mouse button has been clicked
(pressed and released) on a component.

void mouseEntered(MouseEvent e)
2
Invoked when the mouse enters a component.

void mouseExited(MouseEvent e)
3
Invoked when the mouse exits a component.

void mousePressed(MouseEvent e)
4 Invoked when a mouse button has been pressed on a
component.

void mouseReleased(MouseEvent e)
5 Invoked when a mouse button has been released on a
component.

116
Here is the sample syntax for it:

SYNTAX

117
118
Here is the output:

If you put the mouse and click it anywhere beyond the colored text, this will happen:

119
Windows Listener

It is one of the event listener interfaces that could be implemented for


receiving windows events.

The class which processes the WindowEvent should implement this


interface. The object of that class must be registered with a component. The
object can be registered using the addWindowListener () method.

Interface Methods

Sr.No. Method & Description

void windowActivated(WindowEvent e)
1 Invoked when the Window is set to be the active
Window.

void windowClosed(WindowEvent e)
2 Invoked when a window has been closed as a result
of calling dispose on the Window.

void windowClosing(WindowEvent e)
3 Invoked when the user attempts to close the Window
from the Window's system menu.

void windowDeactivated(WindowEvent e)
4 Invoked when a Window is no longer the active
Window.

void windowDeiconified(WindowEvent e)
5 Invoked when a Window is changed from a
minimized to a normal state.

120
void windowIconified(WindowEvent e)
6 Invoked when a Window is changed from a normal
to a minimized state.

void windowOpened(WindowEvent e)
7
Invoked the first time a Window is made visible.

Here is the example:

SYNTAX

121
122
123
124
125
This must be the output:

126
Pointers to Keep in Mind

Event handling is the mechanism that controls the event and decides what should
happen when an event occurs.
An event is a mechanism, by which components inform the program that an
action has occurred. An event can be a mouse action or keyboard entry. On
Java, events are implemented through the use of the classes in the java.awt
event package.
Events are implemented through the use of the classes in the java.awt.event
package.
Common events in Java are:
 ActionEvent,
 FocusEvent
 ItemEvent
 KeyEvent
 MouseEvent
 WindowEvent
 The commonly used event listeners are:
 ActionListener
 FocusListener
 ItemListener
 KeyListener
 MouseListener
 WindowListener

127
Task
Performance
Game
Development
Objective:
At the end of the activity, the students should be able to create a game that
uses Swing components that can generate and handle events.

Software Requirements:
 Netbeans 8.2 or higher
 Java Development Kit (JDK) 7

Procedure:

1. Create a class named TaskPerfGame.

2. Extend the JFrame class and implement either the MouseListener


interface or the KeyListener interface.

3. Add Swing components to the JFrame such as the following:

 JLabel

 JTextField

 JButton

 JCheckBox

 JComboBox

4. Add events to your components by placing statements within the


methods listed below.

5. MouseListener interface methods:

• mouseClicked(MouseEvent e)

• mouseEntered(MouseEvent e)

128
• mouseExited(MouseEvent e)

• mousePressed(MouseEvent e)

• mouseReleased(MouseEvent e)
6. KeyListener interface methods:
• keyPressed(KeyEvent e)
• keyTyped(KeyEvent e)
• keyReleased(KeyEvent e)

7. Inform your instructor once you are done.

Scoring Rubric:

Point Description
76 – The program works and meets all of
100 the specifications.
51 – 75 The program has minor errors.
26 – 50 The program has a number of
syntax errors.
1 – 25 The program produces incorrect
result.
0 No output

129

You might also like