Professional Documents
Culture Documents
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.
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.
OBJECTS CLASSES
Attributes Methods
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
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.
super ();
super (parameter list);
super.parameter = [parameter_value];
(1) Example:
(2) Example:
Class Student refers to Person superclass attributes name and
address.
C. Method Overriding
Example:
Direction: Answer the Word Puzzle by encircling the programming-related words and
describe each term.
3
Lesson User Interfaces
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.
JAVA GUIs
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:
Example:
SYNTAX
containers
components
and
properties
panel adds
to
components
frame adds
to
components
FileName. 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:
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.
GUI in Java and offers new components and implements a concept known as
“pluggable look and feel”.
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.
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:
SYNTAX
FileName.UsingJWindow
Example:
SYNTAX
FileName.UsingJFrame
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
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 (String text, int horizontal Alignment) – constructs a JLabel with the
specified text and horizontal alignments.
JLabel (Icon image, int horizontal Alignment) – constructs a JLabel with the specified
image and horizontal alignment.
JLabel (String text, Icon, int horizontal Alignment) – constructs a JLabel with the
specified text, image, and horizontal alignment.
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
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:
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.
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);
37
Laboratory Exercise
SYNTAX
FileName.UsingJButton
38
JTextField
To create a JTextField object, you can select one (1) from the following
constructors:
o JTextField () – constructs an empty JTextField
39
o JTextField (String Text) – constructs a new JTextfield with an initial
text display.
40
Laboratory Exercise
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
43
JScrollPane
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.
44
JScrollPane sp = new JScrollPane(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
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
SYNTAX
FileName.UsingJScrollPane
46
Lesson
6 Selection Components in OOP
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.
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:
47
Laboratory Exercise
SYNTAX
48
FileName.UsingJCheckBox
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.
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:
50
Laboratory Exercise
SYNTAX
51
FileName.UsingJRadioButton
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.
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:
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
SYNTAX
55
FileName.UsingJList
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.
57
FileName.UsingJComboBox
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.
Creating Menus
Swing provides a set of classes to support the creation of popup and pull-
down menus. The sets contain are:
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
61
When you hover the mouse to each item, this is what’s going to happen:
62
Adding a Toolbar
63
FileName.UsingJToolBar
64
Pointers to Keep in Mind
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.
66
UNIT 2: GRAPHICAL USER INTERFACE – LAYOUTS
Unit Objectives:
At the end of the topic session, the students should be able to:
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.
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.
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:
SYNTAX
70
FileName.LayoutM-FlowLayout
71
BorderLayout
SYNTAX
72
FileName.LayoutMBorderLayout
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
75
Laboratory Exercise
SYNTAX
76
FileName.UsingGridLayout
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.
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
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
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:
81
Laboratory Exercise
82
BoxLayout
83
Here is an example:
SYNTAX
FileName.UsingBoxLayout
84
The output of the program must be:
85
Laboratory Exercise
86
Lesson
2 Multiple Layout Managers
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
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
91
Pointers to Keep in Mind
92
UNIT 3: OOP EVENT HANDLING & LISTENERS
Unit Objectives:
At the end of the topic session, the students should be able to:
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.
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:
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.
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).
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.
FOCUS_FIRST
Specifies the beginning range of focus event ID values.
SYNTAX
96
FOCUS_GAINED
Event type ID indicating that the component gained the input focus.
SYNTAX
FOCUS_LAST
Specifies the ending range of focus event ID values.
SYNTAX
FOCUS_LOST
Event type ID indicating that the component lost the input focus.
SYNTAX
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:
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.
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
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.
99
100
Lesson
2 Event Listeners in Java
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.
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.
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.
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
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
Interface Methods
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.
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:
JLabel
JTextField
JButton
JCheckBox
JComboBox
• 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)
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