Events and the AWT
The objectives of this chapter are:
To understand the principles of the Java 1.1 event model To understand how the event model is used with GUIbased applications
Cohesion and Coupling
A class is cohesive if:
It has few responsibilities and achieves them well A class's responsibilities are logically related
Classes are coupled when:
A change in one necessitates a change in another
Cohesion and coupling often go hand in hand
A class which is not cohesive often requires many associations to fulfil its responsibilities
The addition of a user interface often causes cohesion and coupling problems in OO designs
Should system entities know how to display themselves? If so, they need to be aware of all contexts within which they will be displayed. Should system entities know how to respond to user input? If so, what affect would that have on the structure of the entities?
Different types of Interfaces
Several years ago, GUI applications were the norm.
There were many tools (like Visual Basic) which made it simple to create gui based applications. Within those applications, however, there was tight coupling between the User interface and the System entities
A shift occurred in application development
Installing GUI based applications onto thousands of workstations caused maintenance costs to rise Logistically, there were many challenges for application deployment
Web-application and thin-client development gained interest
The browser was viewed as the "universal client" and HTML was used for the GUI.
Applications where the business logic was tightly coupled to the GUI had to be rewritten.
If the system entities were not coupled to the display logic, then only the
interface would need to be updated.
The Gartner 3-layer Model
The Gartner group has identified 3 type of logic which exist within the typical business application
Presentation: How is data presented to the User Application: How is data processed Data Management: How is data stored and retrieved
In order to have flexibility between the layers, the layers must be loosely coupled rather than tightly coupled.
Presentation Logic Application Logic Data Management Logic
Design Constraints
The Presentation layer is responsible for display
The presentation layer contains objects whose responsibilities focus upon displaying information to the user and receiving input from the user When system entities change, the display must be updated When the user changes the display, the appropriate system entitled must be updated
However, the Presentation layer must only be loosely coupled to the System entities
Presentation layer components are often written by a third party. When GUI components are written, the authors have no concept of the System Entities which are to be displayed
The Application layer is responsible for processing
This layer contains objects whose responsibilities focus on solving the business problem
The application layer must only be loosely coupled to the Presentation layer objects
If the presentation changes, it should not be necessary to change the
system entities
Design Pattern: Observer
To deal with this dilemma, a design pattern called Observer is used With this design pattern, there are two types of entities:
The Observer The Observable
The observable entity encapsulates some data of interest
When that data changes, the entity notifies all observers watching that data
An observer is interested in the data
Observers register with observables to be notified when the observable's data changes
To reduce coupling, all communication conforms to a simple interface
Design Pattern: Observer
implements Observer
Register() update() Register() update() Register()
Observable
implements Observer
update()
implements Observer
public interface Observer { public void update(); }
Applicability to the GUI
A controller object is created to observe the model
The model notifies the observer when the state of the model has changed The controller updates the appropriate GUI objects to display the new state of the model
A controller object is created to observe the GUI
The GUI notifies the controller when the state of the GUI has changed The controller updates the appropriate model objects based on the changes made at the GUI.
This structure is called model-view-controller
Register
Controller
update
Gui Objects Gui Gui Gui
update Register update
Model Objects Gui Gui Gui
Controller
update
View
Model
Applicability to Java
Java provides a series of GUI components.
Many Java components have Listeners Listeners are equivalent to Observers in the Design Pattern
Each Listener must implement a Listener interface
There are Listener interfaces defined based on what data the listener is looking for (ie. Events)
When a user does something in the interface, this produces an Event
The event is included as a parameter to the method defined in the Listener interface
Register
Controller
Gui Objects Gui Gui Gui
update
AWTEvent
An Event is something that the user does at the GUI
Mouse click, key press, etc.
Events are represented by Event Objects
AWTEvent is the abstract superclass to all event objects generated by AWT components
AWT encapsulates all common features of awt events
Each event has an ID Each event has a reference to the source object Each event keeps track of whether it has been consumed or not.
The following slide lists all of the subclasses of AWTEvent defined in the Java API.
AWT Events
The following is a list of events in the java.awt.event package:
ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent HierarchyEvent InputEvent InputMethodEvent ItemEvent KeyEvent MouseEvent PaintEvent TextEvent WindowEvent - Action has occurred (eg. button pressed) - "Adjustable" Component changed - Component Changed - Container changed (add or remove) - Focus Changed - Change in Component Hierarchy - Superclass of KeyEvent and MouseEvent - Text Input Events - Item Selected or Deselected - Keyboard event - Mouse event - Low level; do not use. - Text Changed events - Window related Events
Listener Interfaces
The Following events have Listeners associated with them:
ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent HierarchyEvent InputMethodEvent ItemEvent KeyEvent MouseEvent
TextEvent WindowEvent
- ActionListener - AdjustmentListener - ComponentListener - ContainerListener - FocusListener - HierarchyListener - InputMethodListener - ItemListener - KeyListener - MouseListener - MouseMotionListener - TextListener - WindowListener
How to Use Events
Components defined in the AWT generate AWTEvents Examine the API documentation for the component to see what kinds of events it generates
Identify which events you wish to listen for (some components generate more than one type of event) Identify the Listener class which Listens for that event
Once you have identified the Listener interface, implement the Listener interface
Listener interfaces are usually implemented by controller classes
Your listener class must register with the component to received events
Call the addXXXListener method where XXX is the Event type.
Events Example: Button
A check of the documentation for the button class indicates that it generates ActionEvents
It provides an addActionListener method Documentation provides links to ActionEvent and ActionListener classes
The ActionListener interface defines 1 method
public void actionPerformed(ActionEvent e)
Create a controller class which implements ActionListener
Register an instance of your controller class using the addActionListener method of the Button Class
Events Example: ButtonController
import java.awt.*; import java.awt.event.*; public class ButtonController implements ActionListener { public void actionPerformed(ActionEvent x) { System.out.println("Button was pressed"); } }
Events Example: FrameController
import java.awt.*; import java.awt.event.*; public class FrameController { public static void main(String[] args) { Frame aFrame = new Frame("Test"); Button aButton = new Button("Ok"); ButtonController aController = new ButtonController(); aButton.addActionListener(aController); aFrame.add(aButton); aFrame.setVisible(true); } }
Components and Events
Button
A push button which contains descriptive text Generates ActionEvents when pressed
TextField
A single line of editable text Generates ActionEvents when the return key is pressed within the field Generates TextEvents when text changes
TextArea Provides multiple lines of editable text
Generates TextEvents when text changes
Checkbox
Provides a checkbox with descriptive text Generates an ItemEvent when its state changes
Choice
Provides a drop-down list of selectable items Generates an ItemEvent when an item is selected
Components and Events
Frame/Window
Represents an on-screen Window Generates WindowEvents
List
A scrollable list of selectable items Generates ActionEvent when and item is double clicked Generates ItemEvents when items are selected or deselected
Components and Events
Some Events are common to all AWT Components
Generate FocusEvents when gaining or losing focus Generates ComponentEvents when the component is shown, hidden, moved or resized Generates HierarchyEvents when its component hierarchy changes Generates KeyEvents when the component has focus and the keyboard is pressed or released. Generates MouseEvents when the mouse is clicked, released or moved within the component. Similarly, generates events when the mouse enters or leaves its bounding box on the screen.
Adapter Classes
Some Listener interfaces define several methods
MouseListener defines 5 methods WindowListener defines 7 methods
The Java API provides several Adapter classes which provide empty method implementations of the Listener interfaces
If a programmer wishes to implement only 1 of the WindowListener methods, he/she can subclass WindowAdapter and override the single method that he/she wishes to provide an implementation for
Adapter classes provided are:
ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter