Transcript LECT#09
Lecture 9: Graphical User Interfaces
Objectives
Introduction to events
Introduction GUI
A Brief History
Event Sources and Listeners
The Delegation Model
Example 1: Handling Key Events
Example 2: Handling Mouse Events
Adapter Classes
9Lecture 12
1
Introduction to Events
GUI applications are event-driven. User interaction with the GUI results in events
being generated to inform the application of user actions. Clicking a button,
closing a window, or hitting a key results in an appropriate event being sent to the
application
Events can be generated as a consequence of a person interacting with graphics
components of a program. Examples:
Keyboard events (key up, key down)
Mouse events (mouse move, mouse drag, button up, button down).
Button events (user presses a button)
TextField events (user presses a return)
Menu events (user selects an item from a pull-down menu)
Events can also happen in cases where there is no direct user interaction. For
example, an event may be generated when a timer expires, a counter exceeds a
value, a software or hardware failure occurs, or an application is completed.
9Lecture 12
2
Introduction to Events (cont.)
When studying events and events handling, there are three main categories of classes to deal with:
Event classes
Event source classes
Event listener classes
Event classes represent events and provide a consistent, easy-to-use means of encapsulating events.
Event sources are graphics components (like Buttons, Scollbar, Window) which generate and manage
event listeners. For example, you receive key and mouse events from an applet (see Examples 1 and 2
in this lecture)
Listener classes are classes that implement one or more listener interfaces defined by the
java.awt.event package.
• Event class (e.g. MouseEvent). Contains information about the
event (e.g. mouse location)
• Event listener. Knows what to do when the event occurs. Implements
listener interface (e.g. MouseListener)
• Event source. Keeps a list of listeners and notifies them when the
event occurs
9Lecture 12
3
A Brief History
The original AWT (Abstract Windowing Toolkit)was
suitable for Java applets but not for full-fledged
application development.
AWT 1.1 (JDK 1.1) had better event handling but did
not have enough GUI components and was too
dependent on (nonportable) native code,.
In 1997 Netscape and Sun developed a set of GUI classes
written entirely in Java. The Java Foundation Classes
(JFC), including the Swing component set, were
released with JDK 2.0.
A Swing program can have the same look and feel on a
Mac, Windows, or Unix platform.
9Lecture 12
4
Event Classes & Source classes
EventObject
AWTEvent
ActionEvent
ContainerEvent
AdjustmentEvent
FocusEvent
ComponentEvent
InputEvent
ItemEvent
PaintEvent
TextEvent
WindowEvent
MouseEvent
KeyEvent
ListSelectionEvent
java.awt
java.lang
Objec t
Container
Component
JComponent
com.sun.java.sw ing
JLabel
JList
JOptionPane
JPanel
JPopupMenu
JMenuBar
JScrollPane
JCheckbox
JToggleButton
JRadioButton
AbstractButton
JButton
JMenuItem
JMenu
JTextArea
JTextComponent
JTextField
JPasswordField
Key
Clas s
Pack age
Abstr ac t Clas s
exte nds12
9Lecture
Inte rfa ce
imp leme nts
5
Java Events Classes
At the root of the Java event class hierarchy is EventObject, which is in java.util
(also see Horstmann Chapter 10).
The EventObject contains two methods: getSource() and toString()
which return the source event and the string equivalent of the event respectively.
Event classes contain methods for getting information on the event, for example
the MouseEvent class has methods getX() and getY() returning the
coordinates of the mouse when the event occurs.
Here are some of the event classes which subclass EventObject
ActionEvent : A component-defined action occurred.
ComponentEvent : A component moved, changed size, or changed visibility.
FocusEvent : A component has gained or lost the keyboard focus.
KeyEvent : A keystroke occurred in a Component.
MouseEvent : A mouse action occurred in a Component.
TextEvent : An object’s text changed.
WindowEvent : A window has changed its status.
9Lecture 12
6
Event Sources and Listeners
An object that generates an event is called a source. A source may generate more
than one event.
When an event occurs (or is "fired"), it is received by one or more "listeners"
which act on the event.
Note that an event source and the place where the event is handled can be
separate.
Each event listener is an object of a class that implements a particular type of
listener interface.
A listener class must implement the appropriate interface and all the event
handling logic will go inside the listener class.
The most commonly handled events are those generated by the mouse, the
keyboard, and various controls, such as a push button.
9Lecture 12
7
Event Sources and Listeners
A source must register listeners in order for the listeners to receive notifications
about a specific event.
The source object maintain la list of listener. example. keyboard event implements
KeyListener interface
Registration methods: are dependent on event type . Example KeyListener is
addKeyListener . ActionEvent is addActionEvent
Each component type has the following pair of methods for registering and
unregistering listeners
public void addTypeListener (TypeEvent t) throws java.util.TooManyListnersException
public void removeTypeListener (TypeEvent t)
Here, Type is the name of the event and t is a reference to the event listener. the
TooManyListenersException is thrown in case of sources that allow only one
listener to register.
Notifying many registered listeners for an event is called broadcasting the event.
Event notification in sources that can have only one listener sources is called
unicasting.
9Lecture 12
8
The Delegation Model
EventObject
mouseEvent
keyEvent
windowEvent
User
action
Generate
an event
Notify listener
Trigger an event
Events are sent
from single source
object
Listener implements specific
event handling method
Source Object
Listener Object
Register a listener object
Event Handler
1 Define a class that implements the appropriate listener interface your class provides the
handler by implementing the methods that that are declared by the interface. Ex
public class K implements KeyListener…MouseLisener…WindowListener.
Implement keyPressed,keyReleased, keyTyped
2-Register an instance of the class with the component affected by the event
Ex.
void addxxxListener(xxListener object).
9Lecture 12
9
Example 1: Handling Key Events
In order to handle keyboard events, we must implement the KeyListener
interface:
void keyPressed(KeyEvent ke);
void keyReleased(KeyEvent ke);
void keyTyped(KeyEvent ke);
Note that when a key is pressed a KEY_PRESSED event is generated which
results in calling the keyPressed() event handler.
When the key is released a KEY_RELEASED event is generated which results in
calling the keyReleased() event handler.
If a character is generated by the keystroke, then a KEY_TYPED event is sent and
the keyTyped() handler is invoked.
Thus, you will notice that, each time the user presses a key, at least two and often
three events are generated. If you are interested in all these events then you must
put the appropriate code in all these methods to achieve the behavior you desire.
9Lecture 12
10
Example 1: Handling Key Events (cont.)
Register with the
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class KeyEventHandler extends Applet
implements KeyListener{
private String msg = "";
private int startX = 10, startY = 10;
public void key Pressed(KeyEvent ke){
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke){
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke){
msg += ke.getKeyChar();
repaint();
}
listner
public void init(){
// pass the ref this to add itself as
// a key listener
addKeyListener(this);
//The following method requests that
//this component gets the input focus.
//The component must be visible on the
//screen for this request to be granted
requestFocus();
}
public void paint(Graphics g){
g.drawString(msg,startX,startY);
}
}
9Lecture 12
11
Example 2: Handling Mouse Events
In order to handle mouse events, we must implement the
MouseListener interface which has these five methods:
void mouseClicked(MouseEvent me);
void mouseEntered(MouseEvent me);
void mouseExited(MouseEvent me);
void mousePressed(MouseEvent me);
void mouseReleased(MouseEvent me);
If mouse is clicked and released at the same point, mouseClicked() is invoked.
When the mouse enters a component, the mouseEntered() method is called. When
it leaves, mouseExited() is called.
The mousePressed() and mouseReleased() are invoked when the mouse is
pressed and released respectively
9Lecture 12
12
Example 2: Handling Mouse Events
import java.applet.Applet;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseEventHandler extends Applet implements MouseListener{
public void mouseClicked(MouseEvent me){
System.out.println("Clicked at ("+me.getX()+", "+me.getY()+")");
}
public void mouseEntered(MouseEvent me){
System.out.println("Entered at ("+me.getX()+", "+me.getY()+")");
}
public void mouseExited(MouseEvent me){
System.out.println("Exited at ("+me.getX()+", "+me.getY()+")");
}
public void mousePressed(MouseEvent me){
System.out.println("Pressed at ("+me.getX()+", "+me.getY()+")");
}
public void mouseReleased(MouseEvent me){
System.out.println("Released at ("+me.getX()+", "+me.getY()+")");
}
public void init() {
addMouseListener(this); }}
9Lecture 12
13
Mouse event Example
9Lecture 12
14
Adapter Classes
In order to make the button work, we need a WindowEvent
listener. The obvious way to get such a listener is to write a
listener class that implements the WindowListener interface.
That turns out to be a bad idea., though. Implementing this
interface requires writing seven methods(windowActivated()windowclosed(),
windowIconified,windowOpened.., one for each type of window event. We’re
interested in just one of these events, so we’d end up writing six
methods for events that we don’t need. The java.awt.event
package contains a class named WindowAdapter. This class
implements the WindowListener interface, although the methods
that it provides are all empty. All we have to do is extend
the WindowAdapter class and override the
WindowClosing method, which is the only one we’re
interested in. WindowAdapter is an example of an adapter class .
A class that we can extend instead of implementing an interface.
Java provides matching adapter classes for most interfaces that
have two or more methods.
9Lecture 12
15
Introduction to Adapter Classes
When an interface contains only one method, there’s no need for
an adapter class
Adapter classes save programmer’s time by providing an empty
implementation of Listener’s methods
To use an Adapter you need to subclass it and override only the methods which you
wish to use.
You can define an Adapter class as an inner, anonymous inner or as an external class.
Some adapter classes are:
» java.awt.event.ComponentAdapter
» java.awt.event.FocusAdapter
» java.awt.event.KeyAdapter
»java.awt.event.MouseAdapter
»java.awt.event.MouseMotionAdapter
»java.awt.event.WindowAdapter
9Lecture 12
16