11895 event handling 2
DESCRIPTION
event_handling_TRANSCRIPT
1
Event Handling
in Java
2
Events
• Examples
– Keyboard events - pressing a key, holding a key, releasing a key
– Mouse events - moving the mouse, clicking the mouse
– GUI events - clicking on a button, resizing a window, closing a
window, opening a window
• An event in Java is an object of a particular event class,
that represents some user actions to which the GUI might
respond
• Most often events correspond to user actions, but
sometimes they do not
An event is an action initiated by the user
interacting with the program.
3
Low Level Events
• Low level events represent direct communication from the user
• Low level event examples (all the event classes listed below belong to the java.awt.event package0: – key event - a keyboard key pressed or released - in the KeyEvent class
– focus event – a component got focus, lost focus – in the FocusEvent class
– mouse event - the mouse is moved or dragged, a mouse button is pressed or released, the mouse cursor enters or exits a component - in the MouseEvent class
– component event - a component is hidden, shown, resized, or moved – in the ComponentEvent class
– container event - a component is added to or removed from a container in the ContainerEvent class
– window event - a window is opened, closed, activated, deactivated, etc. - in the WindowEvent class
– paint event - is used to ensure that paint() and update() method calls are handled properly. This event is automatically generated when one of the above methods is called. To be able to implement this event, the programs should continue to override paint() and update() methods. Notice that paint event does not require an action listener!
4
Paint Event
• repaint() method - requests an erase and redraw (update) after a small time delay. When you invoke repaint(), it sends a message to the native GUI to paint. The GUI then repaints some components on it own.
• update() method - erases the component (e.g. by drawing the component in the background colour, which makes it disappear) . Then it calls the paint() method.
• paint() method - does the drawing, using the Graphics object passed to it.
• What triggers a repaint of a GUI container? – adding or deleting a component, making a component visible or invisible, changing
the size or location of a component
– calling validate(). This redoes the layout if necessary deciding on new sizes and locations of all the components in the container. Most often it gets called directly by application programmers, after a frame or other container is been composed but before it has been made visible
– setVisible(true) for containers which will typically call validate()
5
High Level Events
• High level (semantic) events encapsulate the meaning of a user interface component
• High level events usually involve one or more low level events
• High Level Event examples – action event - do a command – ActionEvent class
– adjustment event - represents scrollbar motions such as a value was adjusted – AdjustmentEvent class
– item event - occurs when the user selects a checkbox, choice, or list item, i.e. item state has changed –ItemEvent class
– text event – represents a text component content (value) change – TextEvent class
6
How Do the Low and High Level
Events Work in Java?
• When the user clicks the mouse on a button, then
releases it, the button gets two or three separate,
low level mouse events
– one for mouse down
– one for mouse up
– possibly one for mouse drag (if the user moves the
mouse while the button is pressed)
• However, the button then fires one high level
event only - ActionEvent
7
Event Hierarchy
• Events are organized into hierarchy of event
classes
• Event classes contain data relevant to a
particular event type
• An event is an object of one of the event
classes
8
Event Hierarchy in Java
Libraries
java.util.EventObject
java.awt.AWTEvent
AdjustmentEvent ComponentEvent ActionEvent TextEvent ItemEvent
WindowEvent InputEvent FocusEvent ContainerEvent
MouseEvent KeyEvent
PaintEvent
java.lang.Object
Note: All the events below
this level belong to
java.awt.event package
9
Event Sources
• The type of an event depends on its source
• Example of event sources: – the keyboard
– the mouse
– the GUI components – buttons, text fields, windows
• Event source is an object with the ability to determine when an event has occurred
• An event source generates events by invoking
methods (e.g. e.getSource() method) of one
or more listener objects
10
ActionEvent
• The ActionEvent class contains specific information about the event that occurred
• Two ActionEvent methods are used to obtain the source of the event
– getActionCommand() method of class ActionEvent is used to obtain a string containing the name (e.g. the label on a button, text in a text field) of the event source
– getSource() method returns a reference to the source of the event (e.g. the GUI component that generated the event)
11
Event Driven Interfaces
• An event-driven system waits for something to
happen (an event) in the environment.
• Event-driven application - an input-output model
in which the application implements an event loop
– waits for an event to occur
– responds to the event
– waits for the next event and so on …
– GUIs are event-driven - they generate events when the
user interacts with the GUI
12
Event Driven Programming
• In event driven programming the events “drive”
the execution of the program, e.g. the code is
executed when events are activated
• The program interacts with the user and generates
events based on the external user actions
• Java Visual (Graphical) programming and Visual
Basic programming are event driven
• When writing applets that are using events in Java
we have to import the “events” package java.awt.event.*;
13
Java Event Delegation Model (1)
• Java uses delegation-based model for event
handling
• Java uses event listener to register an event
and event handler to respond to the event
• The use of event listeners in event handling
is called delegation event model
14
Java Event Delegation Model (2)
• An external user’s action on a source object (e.g. the event source) activates an event
• An event listener object (e.g. an object interested in the event source) receives the event. This object is an instance of a class that implements a specific EventListener interface – Example: ActionEvent --> ActionListener
• The source maintains a list containing all the listener objects that have registered to be notified of events of that type
• The transmission of an event from an event source to an event listener involves invoking a method on the listener object by which the source notifies the listener of the occurrence of an event of a specific type – Example: method actionPerformed (ActionEvent e)
– An EventListener interface declares one or more methods which must be defined in the listener class, and which are invoked by the event source in response to each specific event type handled by the interface
• Example:
EventListener method actionPerformed (ActionEvent e)
15
Java Event Delegation Model
Diagram
EventObject
Listener Event
Event Handler Register a listener object
Source Object
User Action
Activate an
event
Generate an
Event
Notify
Listener
16
Java Event Delegation Model for a
Button
ActionEvent
ActionListener
actionPerformed(ActionEvent e) b.addActionListener(this)
The button b
Press a button
Activate an
event
Generate an
Event
Notify
Listener
17
Working with GUIs & Events in
Java
• Display the component in the container (applet)
add( componentName );
• Add an action listener for the component
componentName.
addActionListener( this );
• Write the code to handle the event
18
Button Event Handling Example (1)
DEMO …
19
Button Event Handling Example (2)
public class BGColor extends Applet
implements ActionListener
{ Button redButton;
public void init( ) {
redButton = new Button( "Red" );
redButton.addActionListener ( this );
add( redButton );
}
public void actionPerformed ( ActionEvent e ) {
setBackground ( Color.red );
repaint( ); // updates the applet
}
}
20
Events and Listeners (1)
• The Java standard class library contains several classes that represent typical events
• Components, such as an applet or a button, generate (fire) an event when it occurs
• Objects, called listeners, wait for events to occur. A listener object is an instance of a class that implements a specific listener interface
• A number of listener interfaces are pre-defined and each interface declares the appropriate methods for a specific class of events
21
Events and Listeners (2)
Component
This object may
generate an event
Listener
This object waits for and
responds to an event
When an event occurs, the component calls
the appropriate method of the listener,
passing an (event) object that describes the event
Event
22
Events and Listeners (3)
• Each event is
represented by an
object that gives
information about the
event and identifies the
event source.
• Each event source can
have multiple listeners
registered on it. A
single listener can
register with multiple
event sources.
event source
event listener 1
event listener 2
event listener 3
23
Event Listeners
• A listener object can be registered on a source
object to be notified of the occurrence of all events
of the specific class for which the listener object is
designed
• The occurrence of an event defined by the
specified class will automatically invoke the
matching method in the listener object
• The code in the body of the method is designed by
the programmer to perform the desired action
when the event occurs
24
Examples of Events and Event
Listeners
• User clicks a button, presses <Return> while typing in a text field, or chooses a menu item and an ActionEvent is generated and an ActionListener should be registered
• User closes a window and a WindowEvent is generated, and a WindowListener should be registered
• Component becomes visible and a ComponentEvent is generated, and an ComponentListener should be registered
• Component gets the keyboard focus and a FocusEvent is generated, and a FocusListener should be registered
25
Listener Interfaces
• We can create a listener object by writing a class that implements a particular listener interface
• The Java standard class library contains several interfaces that correspond to particular event categories
• After creating the listener, we add the listener to the component that might generate the event to set up a relationship between the component, generating the event and the event listener
26
Processing an Event in Java (1)
• Register an event listener
– “listens” for events generated by GUI components
– an object of a class from the package
java.awt.event
• Implement an event handler
– a method that is automatically called in response to a
particular type of event
27
Processing an Event in Java (2)
• For each event class there is a corresponding
listener interface defined in Java and
corresponding listener methods (handlers) in
the listener interface
• Example :
– for the event class ActionEvent
– the listener is ActionListener
– and the listener method (handler) is
actionPerformed (ActionEvent e )
28
How to Implement an Event
Handler in Java (1)
• Every event handler requires three separate steps
1. In the declaration for the event handler class, we specify that the class
either implements a listener interface or extends a class that implements
a listener interface
public class MyClass implements ActionListener { … }
2. Code that registers an instance of the event handler class as a listener upon one or more components
someComponent.addActionListener(instanceOfMyClass);
3. Code that implements the methods in the listener interface public void actionPerformed(ActionEvent e) {
//code that reacts to the action... }
29
Example
• How do buttons handle mouse clicks?
– To detect when the user clicks a button, a program must have
an object that implements the ActionListener interface.
– 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 button, it generates an action event
and the button's action listeners are notified. This results in
the call of the action listener's actionPerformed method.
• The single argument to the method is an ActionEvent object that
gives information about the event and its source
30
Handling Events
• A listener object must implement the corresponding listener interface. A listener for a Button source object, for example, must implement the ActionListener interface. The ActionListener interface contains the actionPerformed(ActionEvent e) method. This method must be implemented in the listener class. Upon receiving the notification, the method is executed to handle the event
• An event object is passed to the handling method. The event object contains information relevant to the event type. In the ActionEvent you can use e.getsource() method to obtain the source object to determine whether it is a button or a text box, or a check box.
31
Radio Button Event Example (1)
DEMO…
32
Radio Button Event Example (2)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RadioButtonApplet extends Applet implements ItemListener {
private CheckboxGroup c;
private Checkbox firstCheckbox, secondCheckbox, thirdCheckbox, fourthCheckbox, fifthCheckbox;
public void init() {
setLayout(new GridLayout( 5, 1 ));
c = new CheckboxGroup( );
firstCheckbox = new Checkbox( "first", c, false );
add( firstCheckbox );
firstCheckbox.addItemListener( this );
secondCheckbox = new Checkbox( "second", c, false );
add( secondCheckbox );
secondCheckbox.addItemListener( this );
33
Radio Button Event Example (3)
thirdCheckbox = new Checkbox( "third", c, false );
add( thirdCheckbox );
thirdCheckbox.addItemListener( this );
fourthCheckbox = new Checkbox( "fourth", c, false );
add( fourthCheckbox );
fourthCheckbox.addItemListener( this );
fifthCheckbox = new Checkbox( "fifth", c, false);
add( fifthCheckbox );
fifthCheckbox.addItemListener( this );
} // end of init
public void itemStateChanged( ItemEvent e) {
String itemLabel = e.getItem().toString();
showStatus( "You have chosen " + itemLabel );
}
}
34
Choice Event Example (1)
DEMO…
35
Choice Event Example (2) import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ChoiceApplet extends Applet
implements ItemListener {
private Choice chooseColor;
private Color backColor;
private int choiceIndex;
public void init() {
chooseColor = new Choice();
chooseColor.add("White");
chooseColor.add("Green");
chooseColor.add("Red");
chooseColor.addItemListener(this);
add(chooseColor);
}
36
Choice Event Example (3)
public void paint( Graphics g ) {
switch (choiceIndex) {
case 0 : backColor = Color.white; break;
case 1 : backColor = Color.green; break;
case 2 : backColor = Color.red; break;
default : backColor = Color.white;
}
setBackground( backColor );
}
public void itemStateChanged( ItemEvent e ) {
if ( e.getSource() == chooseColor ) {
choiceIndex = chooseColor.getSelectedIndex();
repaint();
}
}
}
37
List Event Example (1)
DEMO…
38
List Event Example (2)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ListApplet extends Applet implements ItemListener {
private List shapeList;
private int listIndex;
private Shape myShape;
public void init() {
shapeList = new List(3, false);
shapeList.add( "Line" );
shapeList.add( "Oval" );
shapeList.add( "Rectangle" );
shapeList.addItemListener(this);
add(shapeList);
}
public void paint( Graphics g ) {
myShape = new Shape ( listIndex, 0 );
myShape.display( g );
}
39
List Event Example (3)
public void itemStateChanged( ItemEvent e ) {
if ( e.getSource() == shapeList ) {
listIndex = shapeList.getSelectedIndex();
String message = "";
if ( listIndex == 1 )
message += "n";
message += " " + shapeList.getItem( listIndex );
showStatus( "You have choosen to draw a" + message );
repaint();
}
}
}
40
List Event Example (4) class Shape {
private int size;
private int shapeNumber;
// class Shape constructor
Shape(int shape, int shapeSize) {
shapeNumber = shape;
size = shapeSize;
}
public void display(Graphics g) {
int xBegin, yBegin, xEnd, yEnd, width, higth;
xBegin = (int) (Math.random() * 100) + 20;
yBegin = (int) (Math.random() * 100) + 20;
xEnd = (int) (Math.random() * 100) + 20;
yEnd = (int) (Math.random() * 100) + 20;
width = (int) (Math.random() * 50) + 20;
higth = (int) (Math.random() * 50) + 20;
switch (shapeNumber) {
case 0:
g.drawLine(xBegin, yBegin, xEnd, yEnd); break;
case 1:
g.drawOval(xBegin, yBegin, width, higth); break;
case 2:
g.drawRect(xBegin, yBegin, width, higth); break;
}
}
}
41
List Event Example Explained (5)
• The program consists of two classes and they will be saved in the same file
• The name of the file should be the same as the name of the first class – e.g. ListApplet.java
• Class constructors are special methods that have the same name as the name of the class, do not return any value and access specifiers are not included in the constructor declaration
• The role of the constructor is to assign values to the private variables in the class and when executed to create an object of this class with the values specified in the constructor call
• The constructor is always called using the new method I n order to create a new object of the specified class
• We have been using constructors many times from Java libraries – Font, Choice, Button, Label are both classes names and constructors names
• Example Font font1 = new Font( “Times New Roman”, Font.BOLD, 14 )
Constructor (method) name Class name