You are on page 1of 50

Event Driven Programming

Functionality behind GUI

Outline
Explain the concept of event-driven programming Understand event, event source, and event classes Declare listener classes and write the code to handle events Register listener objects in the source object Understand how an event is to be handled Illustrate the concepts of ActionEvent, WindowsEvent, MouseEvent, and KeyEvent Use the Timer class to control animations Java Applet
2

General structure of event-driven programming


1. Start o by seKing up its internal state, then control is handed over to the event loop provided by the runtime. 2. Wait for the event loop to detect user actions (translated to events). These events are handled by the program one at a time. 3. Terminate when the user performs the exit action.

General structure of event-driven programming


Source 1

Event Loop
events
Event Queue Dispatcher

Handler 1

Source 2

Handler 2 Handler n

Source m

Event Loop is the heart of event-driven programming begin set up mapping from events to responses while (not done) { wait for event read event map event to response call response function }
4

Windows: an example
PowerPoint
Windows OS Event Queue and Dispatcher

IE

Event Loop
Input Devices Event Queue Event Dispatcher

mouse up (10,20)

while(!done) { evt = dequeue_event(); dispatch_event(evt); key down (h) repaint_screen(); key up (h) } key down (i)
Exists in every application Usually handled for you by UI framework

Event Loop
Input Devices Event Queue Event Dispatcher

mouse up (10,20)

while(!done) { evt = dequeue_event(); dispatch_event(evt); key down (h) repaint_screen(); key up (h) } key down (i) Blocks until an event arrives

Event Loop
Input Devices Event Queue Event Dispatcher

mouse up (10,20)

while(!done) { evt = dequeue_event(); dispatch_event(evt); key down (h) repaint_screen(); key up (h) } key down (i) Most of the work happens here

Event generation
From the user
o o o o

Mouse-click on a buKon Close/open/resize a window Paint a picture Enter a key Timer Scheduling Exception/Error USB drive CD/DVD

Raw events

From the operation system


o o o

From external hardware


o o

Event handling: the basic procedure for one event


What need to be done when an event occurs?
1. Identication of the event o event source the object where an event occurs o event type - multiple types of events may come from the same source; o other properties - for example, time, location etc. 2. Event handling o who - discovering the handler(s) o how - actions to be taken (handling or callback functions to be executed)
10

Event handling: challenges


More than one event may occur simultaneously
1. 2. 3. Queuing and scheduling - what are the events and in which order they should be handled? Registration and notication - who (more than one party may be interested in the same event) is going to handle a certain event? Handling what are the actions to be taken to handle a certain event?

11

Event handling: summary


Event source(object)/type
o Where is the event generated and with what type o Here, the where object is called trigger or generator

Event registration
o Who is interested in what event with what type o Here, the who object is called listener

Event handling callback


o What method to be executed o The method is called handler part of listener

12

Event handling in Java GUI


Java has a built-in event-handling model GUI is one of the most typical event-driven applications
ActionEvent AdjustmentEvent EventObject AWTEvent ComponentEvent ItemEvent TextEvent ContainerEvent FocusEvent InputEvent PaintEvent WindowEvent KeyEvent MouseEvent

13

Dispatching Events
mouse down (10,50)
Window

Panel

Button

Textbox

Panel

Button

Button

function onMouseDown(evt) { // do something... }


14

Dispatching Events
mouse down (10,50)
Window

Panel

Button

Textbox

Panel

Button

Button

function onMouseDown(evt) { // do something... }


15

Dispatching Events
mouse down (10,50)
Window

Panel

Button

Textbox

Panel

Button

Button

function onMouseDown(evt) { // do something... }


16

Dispatching Events
mouse down (10,50)
Window

Panel

Button

Textbox

Panel

Button

Button

function onMouseDown(evt) { // do something... }


17

Dispatching Events
mouse down (10,50)
Window

Panel

Button

Textbox

Panel

Button

Button

function onMouseDown(evt) { // do something... }


18

Implementing Listeners
Listener is an interface
o Overwrite abstract handler methods

Several common techniques


o Component is listener o Inner class is listener o Separate class is listener

19

Component-as-Listener
Component implements listener interface
o addXListener(this)

Useful for internal event processing


o Widgets: buKon, scrollbar,
public class myButton extends JButton implements ActionListener { public myButton() { addActionListener(this); } void actionPerformed(ActionEvent e) { // handle the event } }
20

Inner class is listener

Inner Listener

o Often anonymous (in addXListener method) o Use adapter classes to simplify

Useful for simple listeners


o Simplies component, localizes handlers o Inner class has private access o Some implementation constraints
public class myButton extends JButton { public myButton() { addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // handle the event }); } }
21

Adapters
Predened do nothing listener class
o Handler methods empty

Subclass to override handler method


o Dont need to dene all methods o Useful for simple inner classes
public class myLabel extends JLabel { public myLabel() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { // handle the event } }); } }
22

Separate Listener
Existing (or specialised) separate class
o Implement interface o addXListener(listener)

Useful for complex listeners


o Separate event processing from display o Reusable listener

Example: ShowEvent
o mouseTarget: inner listener o keyTarget: inner listener, separate listener o moveTarget: component-as-listener

Run

Source code: Download->codes.zip (ShowEvent)


23

Java event properties


An event object contains various properties pertinent to the event. Identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as buKon actions, window events, component events, mouse movements, and keystrokes.

24

Java user actions


User Action
Click a button Window opened, closed, etc. Mouse pressed, released, etc. Mouse moved, dragged, etc. Key released, pressed, etc. Click a check box Click a radio button Press return on a text field Select a new item

Source Object
JButton Window Component Component Component JCheckBox JRadioButton JTextField JComboBox

Event Type Generated


ActionEvent WindowEvent MouseEvent MouseMotionEvent KeyEvent ItemEvent, ActionEvent ItemEvent, ActionEvent ActionEvent ItemEvent, ActionEvent

25

Java Event Model


Trigger an event User Action source: SourceClass +addXListener(listener: XListener) XListener

+handler(event: XEvent)

(a) A generic source component with a generic listener

Register by invoking source.addXListener(listener); listener: ListenerClass

source: JButton +addActionListener(listener: ActionListener) Register by invoking source.addActionListener(listener);

ActionListener

+actionPerformed(event: ActionEvent)

(b) A JButton source component with an ActionListener

listener: CustomListenerClass

26

Java Event Model


source: SourceClass +addXListener(XListener listener) An event is triggered Keep it a list source: JButton +addActionListener(ActionListener listener) An event is triggered Keep it a list

event: XEvent

Invoke listener1.handler(event) listener2.handler(event) listenern.handler(event)

listener1 listener2 listenern

event: ActionEvent

Invoke listener1.actionPerformed(event) listener2.actionPerformed(event) listenern.actionPerformed(event)

listener1 listener2 listenern

(a) Internal function of a generic source object

(b) Internal function of a JButton object

+handler(

+handler(

27

Java Event-Driven Model: an example


ActionListener listener = new ActionListener(); void actionPerformed(ActionEvent e) { // handle the event } //event registration Event source Event registration Event handler Event Listener

(new JButton("OK")).addActionListener(listener);

28

Java event class, listener, and handlers


Event Class
ActionEvent WindowEvent

Listener Interface
ActionListener WindowListener

Listener Methods (Handlers)


actionPerformed(ActionEvent) windowClosing(WindowEvent) windowOpened(WindowEvent) windowClosed(WindowEvent) windowIconified(WindowEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) itemStateChanged(ItemEvent) componentAdded(ContainerEvent) componentRemoved(ContainerEvent)
29

MouseEvent

MouseListener

KeyEvent ItemEvent ContainerEvent

KeyListener ItemListener ContainerListener

Event Sources
Users actions:
o Action Events (BuKon) o Mouse Events (Mouse) o Key Events (Keyboard) o Window Events (Interaction)

Internal events (from Operation System)


o Action Events (Timer)

30

Handling Action Events: class ActionEvent


java.util.EventObject
+getSource(): Object Returns the object where the event initially occurred.

java.awt.event.AWTEvent java.awt.event.ActionEvent
+getActionCommand(): String +getModifier(): int +getWhen(): long Returns the command string associated with this action. For a button, its text is the command string. Returns the modifier keys held down during this action event. Returns the timestamp when this event occurred.

31

Handling Action Events: a JButton example


Two buKons OK and Cancel in a window. A message is displayed on the console to indicate which buKon is clicked, when a buKon is clicked.
public class TestActionEvent extends JFrame { // Create two buttons private JButton jbtOk = new JButton("OK"); private JButton jbtCancel = new JButton("Cancel"); public TestActionEvent() { getContentPane().setLayout(new FlowLayout()); // Add buttons to the frame getContentPane().add(jbtOk); getContentPane().add(jbtCancel); // to be continued...

Run

Source code: Download->codes.zip (TestActionEvent.java)


32

// Create a listener object ButtonListener btListener = new ButtonListener(); // Register listeners jbtOk.addActionListener(btListener); jbtCancel.addActionListener(btListener); }

Event source

Event registration

Event listener

public static void main(String[] args) { TestActionEvent frame = new TestActionEvent(); ... } } class ButtonListener implements ActionListener { /** This method will be invoked when a button is clicked */ public void actionPerformed(ActionEvent e) { System.out.println("The " + e.getActionCommand() + " button is " + "clicked at\n } }
33

Event handler, part of the event listener

" + new java.util.Date(e.getWhen()));

Handling Action Events: a Timer example


The javax.swing.Timer class is a source component that automatically res ActionEvents at a predened rate.
javax.swing.Timer
+Timer(delay: int, listener: ActionListener) +addActionListener(listener: ActionListener): void +start(): void +stop(): void +setDelay(delay: int): void Creates a Timer with a specified delay in milliseconds and an ActionListener. Adds an ActionListener to the timer. Starts this timer. Stops this timer. Sets a new delay value for this timer.

The Timer class can be used to control animations. For example, you can use it to display a moving message.

34

public class AnimationDemo extends JFrame { public AnimationDemo() { // Create a MovingMessagePanel for displaying a moving message MovingMessagePanel p = new MovingMessagePanel("message moving?"); getContentPane().add(p); // Create a timer for the listener p Timer timer = new Timer(100, p); timer.start(); } public static void main(String[] args) { AnimationDemo frame = new AnimationDemo(); ... } } class MovingMessagePanel extends JPanel implements ActionListener { private String message = "Welcome to Java"; private int xCoordinate = 5; private int yCoordinate = 20; //to be continued...
35

public MovingMessagePanel(String message) { this.message = message; } /** Handle ActionEvent */ public void actionPerformed(ActionEvent e) { repaint(); } /** Paint message */ public void paintComponent(Graphics g) { super.paintComponent(g); if (xCoordinate > getWidth()) xCoordinate = -100; xCoordinate += 2; g.drawString(message, xCoordinate, yCoordinate); } }

Source code: Download->codes.zip (AnimationDemo.java)


36

Handling Window Events: an Example


Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconied, and deiconied. This program creates a frame, listens to the window events, and displays messages on the console to indicate events that are occurring.

Run

Source code: Download->codes.zip (TestWindowEvent.java)

37

public class TestWindowEvent extends JFrame implements WindowListener { public static void main(String[] args) { TestWindowEvent frame = new TestWindowEvent(); ... } public TestWindowEvent() { addWindowListener(this); } /* MUST override all 7 methods: windowDeiconified, windowIconified, windowActivated, windowDeactivated, windowOpened, windowClosing, windowClosed or implement WindowAdapter instead of WindowListner*/ public void windowDeiconified(WindowEvent event) { System.out.println("Window deiconified"); } ...

Event source and event listener are the same object


// Register listener

38

Handling Mouse Event: class MouseEvent


java.awt.event.InputEvent
+getWhen(): long +isAltDown(): boolean +isControlDown(): boolean +isMetaDown(): boolean +isShiftDown(): boolean Returns the timestamp when this event occurred. Returns whether or not the Alt modifier is down on this event. Returns whether or not the Control modifier is down on this event. Returns whether or not the Meta modifier is down on this event Returns whether or not the Shift modifier is down on this event.

java.awt.event.MouseEvent
+getButton(): int +getClickCount(): int +getPoint(): java.awt.Point +getX(): int +getY(): int Indicates which mouse button has been clicked. Returns the number of mouse clicks associated with this event. Returns a Point object containing the x and y coordinates. Returns the x-coordinate of the mouse point. Returns the y-coordinate of the mouse point.

39

Handling Mouse Events: listeners


Java provides two listener interfaces, MouseListener and MouseMotionListener, to handle mouse events. The MouseListener listens to actions such as when the mouse is pressed, released, clicked (pressed+released), entered, or exited. The MouseMotionListener listens to actions such as dragging or moving the mouse.

40

Handling Mouse Events: listeners


java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void +mouseReleased(e: MouseEvent): void +mouseClicked(e: MouseEvent): void +mouseEntered(e: MouseEvent): void +mouseExited(e: MouseEvent): void Invoked when the mouse button has been pressed on the source component. Invoked when the mouse button has been released on the source component. Invoked when the mouse button has been clicked (pressed and released) on the source component. Invoked when the mouse enters the source component. Invoked when the mouse exits the source component.

java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void +mouseMoved(e: MouseEvent): void Invoked when a mouse is moved with a button pressed. Invoked when a mouse is moved without a button pressed.

41

Handling Mouse Events: a moving message example Objective: Create a program to display a message in a panel. The message moves as the mouse is dragged and is always displayed at the mouse point.
public class MoveMessageDemo extends JFrame { public MoveMessageDemo() { getContentPane().add(new MoveMessagePanel("Welcome to Java")); } public static void main(String[] args) { MoveMessageDemo frame = new MoveMessageDemo(); ... } } // to be continued...

Run

Source code: Download->codes.zip (MoveMessageDemo.java)


42

class MoveMessagePanelNew extends JPanel implements MouseMotionListener { private String message = "Welcome to Java"; private int x = 20; private int y = 20;

public MoveMessagePanel(String s) { message = s; addMouseMotionListener(this); } protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, x, y); } public void mouseDragged(MouseEvent e) { x = e.getX(); y = e.getY(); repaint(); } public void mouseMoved(MouseEvent e) {} } 43

Handling Keyboard Events: listener and handlers


To process a keyboard event, use the handlers in the KeyListener interface:
o keyPressed(KeyEvent e) - called when a key is pressed o keyReleased(KeyEvent e) - called when a key is released o keyTyped(KeyEvent e) - called when a key is pressed and then released

A related listener: FocusListener


o focusGained (FocusEvent e): keyboard focus gained o focusLost (FocusEvent e): keyboard focus lost

44

Handling Keyboard Events: class KeyEvent


Methods: Keys: Home getKeyChar() method End getKeyCode() method Page Up Page Down Up Down java.awt.event.InputEvent Left Right
java.awt.event.KeyEvent
+getKeyChar(): char +getKeyCode(): int

VK_HOME VK_End VK_PGUP VK_PGDN VK_UP VK_DOWN VK_LEFT VK_RIGHT

Returns the character associated with the key. Returns the integer keyCode associated with the key.

45

Handling Keyboard Events: an example


Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys.
public class KeyboardEventDemo extends JFrame { private KeyboardPanel keyboardPanel = new KeyboardPanel(); public KeyboardEventDemo() { getContentPane().add(keyboardPanel); //create UI keyboardPanel.setFocusable(true); //set focus } public static void main(String[] args) { KeyboardEventDemo frame = new KeyboardEventDemo(); ... } } // to be continued...

Run

Source code: Download->codes.zip (KeyboardEventDemo.java) 46

class KeyboardPanel extends JPanel implements KeyListener { private int x=100; private int y=100; private char keyChar=A; public KeyboardPanel() { addKeyListener(this); } protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(String.valueOf(keyChar), x, y); } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN: y += 10; break; case KeyEvent.VK_UP: y -= 10; break; case KeyEvent.VK_LEFT: x -= 10; break; case KeyEvent.VK_RIGHT: x += 10; break; default: keyChar = e.getKeyChar();

} repaint(); } //empty implementation for keyReleased and keyTyped }


47

Director-as-handler
public class Director extends JPanel implements ActionListener { /** * Constructs a Director to run the program. * * @param args command line arguments (currently unused) */ public Director(JFrame window, String[] args) { ... } private JComponent makeInterface() { JPanel p = ...; JButton quit = new JButton("Goodbye!"); quit.addActionListener(this); p.add(quit); return p; } public void actionPerformed(ActionEvent e) { if (e.getCommand.equals("Goodbye!")) { system.exit(0); } } }
48

Example: ColorMatcher
Level 1: a simple buKon
o ActionEvent/ActionListener

Level 2: sliders to set the color


o ChangeEvent/ChangeListener

Level 3: radio buKons


o ActionEvent/ActionListener

Level 4: check box


o ItemEvent/ItemListener

Source code: Download->codes.zip (ColorMatcher1-4)

49

Next on Thursday
Java Applet

50

You might also like