GUI Programming in Java:
Event Handling
Event-Driven
Programming
Procedural programming is executed
in procedural order.
In event-driven programming, code is
executed upon activation of events.
Events and Listeners
An event can be defined as a type of signal to the
program that something has happened.
The event is generated by external user actions
such as mouse movements, mouse button clicks,
and keystrokes, or by the operating system, such
as a timer.
Events are responded to by event listeners
The Delegation Model
Register by invoking
source.addXListener(listener);
Trigger an event
User source: SourceClass listener: ListenerClass
Action
+addXListener(XListener listener)
Keep it a list
XListener
event: XEvent listener1
Invoke listener2
listener1.handler(event) …
+handler(XEvent event)
listener2.handler(event) listenern
…
listenern.handler(event)
Internal function of the source object
+handler(
XEvent
Event-generating Objects send Events to Listener Objects
Each event-generating object (usually a component) maintains a set of
listeners for each event that it generates.
To be on the list, a listener object must register itself with the event-
generating object.
Event Classes
We will focus on ActionEvent and ListSelectionEvent
Selected User Actions
Source Event Type
User Action Object Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Select an item from a List JList ListSelectionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Any Component MouseEvent
Key released, pressed, etc. Any Component KeyEvent
Java AWT Event
Listener Interfaces
ActionListener KeyListener
AdjustmentListener MouseListener
ComponentListener MouseMotionListener
ContainerListener
TextListener
FocusListener
WindowListener
ItemListener
ListSelectionListener
All are in the java.awt.event or javax.swing.event package
All are derived from EventListener in the java.util package
OTE: any object that will respond to an event must implement a listener interf
How to Implement a Listener
Interface
Use the implements keyword in the class
declaration
Register the object as a listener for a
component’s event, using the component’s
addXListener method. (where X is the type
of event). (Typically done in constructor)
Declare and fully define all methods for the
interface that you are implementing
Requires:
Complete method signature
Method body
Selected Event Handlers
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
ListSelection ListSelection valueChanged
Event Listener (ListSelectionEvent)
Handling Simple Action Events
The method for
responding to an
Action event.
Implementing the
listener interface
Registering the
frame to be a
listener for action
events generated
by the two buttons
Handling Simple Action Events –
a closer look at the event-handling method
actionPerformed is a method
required for all ActionListeners
An Event object’s getSource()
method returns a reference
to the Component object that
generated the event.
Alternative Approaches to
Listening
Implement the listener with the main
application class, and have the one listener
assigned to all components generating the events
This is the approach I generally use with my examples
Advantage: simplicity for beginner programmers
Disadvantage: event-handler method may require if-
statement or switch with several branches when
multiple components generate the event
Use inner classes to implement the listeners
and create a different instance as each
component’s listener.
Named inner class or anonymous inner class (This is
the approach used in the textbook most of the time)
Advantage: no need to test within the listeners for
determining which component sent the event. Each
component has its own dedicated listener
Disadvantage: harder to understand for novice
programmers
Example with
named inner
classes, one for
listening to each
button
Inner class
has direct
access to all
members
(even private)
of the outer
class
Example with
anonymous inner
classes, one for listening
to each button
Working with JLabel,
JTextField, JTextArea, JList,
JComboBox, and
JRadiobutton
JLabel
Swing class for a non-editable text
display
Typical constructor:
JLabel(stringValue)
Other Useful Methods:
getText() – returns a string containing
the text in the label component
setText(String) – sets the label
component to contain the string value
JTextField
Swing class for an editable text display
Many constructors possible – here’s one:
JTextField(columnWidth)
Will instantiate a text field component of the specified
width (width is approximate number of characters visible).
Some useful methods:
getText() – returns the text value in the text field
getSelectedText() – returns the text value that
has been highlighted in the text field
setText(stringValue) – sets the text value to the
indicated argument
append(stringvalue) – appends the text value of
the string to the already existing text in the
component
JTextArea
Swing class for an editable text display
Many constructors possible – here’s one:
JTextArea(rowHeight , columnWidth)
Will instantiate a text area component of the specified width
and height (width is approximate number of characters
visible, height is approximate number of text lines visible)
Some useful methods:
getText() – returns the text value in the text field
getSelectedText() – returns the text value that has
been highlighted in the text field
setText(stringValue) – sets the text value to the
indicated argument
append(stringvalue) – appends the text value of
the string to the already existing text in the
component
Note use of getText, setText, getSelectedText and
append methods.
JList
Swing GUI component that presents a list of items
Many constructors…here’s one:
JList(sourceArray);
Produces a ListSelectionEvent
Handling this event by implementing a ListSelectionListener
Need to import javax.swing.event package for this
Some useful methods:
addListSelectionListener – specify which objects will respond to list
selection event
setListData – indicate the source of data for this list (e.g. an array)
getSelectedIndex – identify the current selection from the list (0-
based) -- -1 indicates nothing is selected from list.
setFixedCellHeight and setFixedCellWidth – indicate pixel size of
each item of the list.
JList Example 1: using lists, text fields, labels, and buttons
Implementing listeners
components
List’s data source
JList Example 1: using lists, text fields, labels, and buttons (con’t.)
When array changes, refresh the list
valueChanged is the ListSelectionListener event handler method
Use list index tp get
associated array element
st Example 2: slightly more complicated…data source is an array of objects
This is the class being used
for the array associated with the JList.
toString is a method
that overrides the
Object class’s
method of the same
name. This
determines what
will be displayed in
the JList.
st Example 2: slightly more complicated…data source is an array of objects
st Example 2: slightly more complicated…data source is an array of objects