event-driven programming with the java event model...6 general structure of event-driven general...

34
CPE203/CSC203 Software Systems and Models CPE203/CSC203 Software Systems and Models Event-driven Programming with the Java Event Model Event-driven Programming with the Java Event Model Dr Zhou Suiping Office: N4-02-C87 Phone: 6790 6263 Email: [email protected] Dr Zhou Suiping Office: N4-02-C87 Phone: 6790 6263 Email: [email protected]

Upload: others

Post on 01-Feb-2020

23 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

CPE203/CSC203Software Systems and Models

CPE203/CSC203Software Systems and Models

Event-driven Programming with the Java Event Model

Event-driven Programming with the Java Event Model

Dr Zhou SuipingOffice: N4-02-C87Phone: 6790 6263Email: [email protected]

Dr Zhou SuipingOffice: N4-02-C87Phone: 6790 6263Email: [email protected]

Page 2: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

2

Outline Outline

�Basic concepts of event-driven programming

�General structure of event-driven programming�Event registration and handling

�Some common events in Java GUI programming�ActionEvent, WindowsEvent, MouseEvent, and KeyEvent

�How to use the Timerto control animations�This is related to Lab 1 & 2

�Basic concepts of event-driven programming

�General structure of event-driven programming�Event registration and handling

�Some common events in Java GUI programming�ActionEvent,WindowsEvent,MouseEvent, and KeyEvent

�How to use the Timerto control animations�This is related to Lab 1 & 2

Page 3: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

3

Procedural programming Procedural programming

�Procedural programming is executed in procedural order.

1.Start off by setting its internal state.2.Read data either from the user input or

from data files. 3.Perform computation, etc.

4.Output the results.

�The sequence of operations for an application is determined by a central controlling program (e.g., a main procedure).

�Procedural programming is executed in procedural order.

1.Start off by setting its internal state.2.Read data either from the user input or

from data files. 3.Perform computation, etc.

4.Output the results.

�The sequence of operations for an application is determined by a central controlling program (e.g., a main procedure).

1. Initialize

2. Read Data

3. Process Data

4. Output Results

Page 4: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

4

Event-driven programming Event-driven programming

�In event-driven programming, code is executed upon activation of events.�Not sequential execution: The sequence of operations for an

applicationis determined by the generation of events.�Usually, no end: wait and listen

�An event can be defined as a type of signalto the program, notifying that something is happening.�An event can be generated by external user actionssuch as mouse

movements, mouse clicks, and keystrokes, or by the operating system, such as a timer, and an error.

�In event-driven programming, code is executed upon activation of events.�Not sequential execution: The sequence of operations for an

applicationis determined by the generation of events.�Usually, no end: wait and listen

�An event can be defined as a type of signalto the program, notifying that something is happening.�An event can be generated by external user actionssuch as mouse

movements, mouse clicks, and keystrokes, or by the operating system, such as a timer, and an error.

Page 5: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

5

Event-driven programming Event-driven programming

�Applications�Operation systems : Windows, Mac OS X,

Unix/Linux, etc.�Embedded systems : television, hand phone,

xbox, etc.�Web applications and services : online purchase,

e-commerce, etc.�GUI (Graphical User Interface) applications.

�Applications�Operation systems : Windows, Mac OS X,

Unix/Linux, etc.�Embedded systems : television, hand phone,

xbox, etc.�Web applications and services : online purchase,

e-commerce, etc.�GUI (Graphical User Interface) applications.

Page 6: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

6

General structure of event-driven programming

General structure of event-driven programming

1.Start off by setting up its internal state, then control is handed over to the event loopprovided by the runtime.

2.Wait for the event loop todetectuser actions (translated to events). These events are handledby the program one at a time.

3.Terminate when the user performs the exitaction.

Page 7: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

7

General structure of event-driven programming (Cont’d)

General structure of event-driven programming (Cont’d)

Handler 1

Handler 2

Event QueueDispatcher

events

Handler n

Source 1

Source 2

Source m

Event Loop

Page 8: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

8

Windows OS: an example of event handling

Windows OS: an example of event handling

PowerPoint

IEWindows OSEvent Queue

and Dispatcher

Page 9: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

9

Event generation Event generation

�From the user�Mouse-click on a button�Close/open a window�Paint a picture�Enter a key

Raw events

�From the operation system�Timer�Scheduling�Exception/Error

�From external hardware�USB drive�CD/DVD�Printer

Page 10: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

10

The basic procedure event handling The basic procedure event handling

What need to be done when an event occurs?

1.Identification of the event�event source–the object where an event occurs�event type-multiple types of events may come from

the same source;�other properties-for example, time, location etc.

2.Event handling�whois going to handle to event: discovering the

event handler�how to handle the event: actions to be taken

(methods or callback functions to be executed)

Page 11: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

11

Event handling: challenges Event handling: challenges

More than one event may occur simultaneously.For example, ringing bell, ringing phone, and crying baby when a mother is cooking at home. How to handle this “messy”scenario?

�Queuing and scheduling-what are the events and in which order they should be handled?

�Registrationand notification-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?

JVM greatly simplifies this procedurefor Java programmers!

Page 12: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

12

Event handling: some concepts in Java programming

Event handling: some concepts in Java programming

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

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

�Event handling callback�What method to be executed�The method is called “handler”–part of“listener”

Page 13: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

13

Events in Java GUI programming Events in Java GUI programming

�An event object contains various properties pertinent to the event.�All Java events is a subclass of theEventObjectclass�Subclasses of EventObjectdeal with special types of events, such as

button actions, window events, mouse movements, and keystrokes, etc.

�Obtain useful information from an event�getSource(): returns the source object for the event�getActionCommand(): returns the command string associated with

the action�getWhen():returns the timestamp when the event occurred

�An event object contains various properties pertinent to the event.�All Java events is a subclass of theEventObjectclass�Subclasses of EventObjectdeal with special types of events, such as

button actions,window events,mouse movements, and keystrokes,etc.

�Obtain useful information from an event�getSource():returns the source object for the event�getActionCommand():returns the command string associated with

the action�getWhen():returns the timestamp when the event occurred

Page 14: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

14

User actions, events and event source

User actions, events and event source

SourceEvent TypeUser ActionObjectGenerated

Click a buttonJButtonActionEventClick a check boxJCheckBoxItemEvent, ActionEventClick a radio buttonJRadioButtonItemEvent, ActionEventPress return on a text fieldJTextFieldActionEventSelect a new itemJComboBoxItemEvent, ActionEventWindow opened, closed, etc.WindowWindowEventMouse pressed, released, etc.ComponentMouseEventMouse moved, dragged, etc.ComponentMouseMotionEventKey released, pressed, etc. ComponentKeyEvent

Page 15: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

15

Java event model Java event model

source: SourceClass

+addXListener(XListener listener)

listener: ListenerClass UserAction

Trigger anevent

XListener

+handler(XEvent event)

Internal function of thesourceobject

event:XEventlistener1listener2…listenern

Register byinvokingsource.addXListener(listener);

Keep it a list

Invokelistener1.handler(event)listener2.handler(event)…listenern.handler(event)

Event sourceEvent listener

Page 16: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

16

Java event model: an example Java event model: an examplesource: JButton

+addActionListener(ActionListener listener)

listener: ListenerClass

ActionListener

+actionPerformed(ActionEvent event)

Register by invokingsource.addActionListener(listener);

ActionListenerlistener = new ActionListener();

void actionPerformed(ActionEvente) {

// handle the event

}

//event registration

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

Event handler

OK

Event source

Event Listener

Event registration

Page 17: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

17

Java event class, listener, and handlers Java event class, listener, and handlers

Event ClassListener InterfaceListener Methods (Handlers)

ActionEventActionListeneractionPerformed(ActionEvent)ItemEventItemListeneritemStateChanged(ItemEvent)

WindowEventWindowListenerwindowClosing(WindowEvent)windowOpened(WindowEvent)windowClosed(WindowEvent)windowIconified(WindowEvent)…

ContainerEventContainerListenercomponentAdded(ContainerEvent)componentRemoved(ContainerEvent)

MouseEventMouseListenermousePressed(MouseEvent)mouseReleased(MouseEvent)mouseClicked(MouseEvent)…

KeyEventKeyListenerkeyPressed(KeyEvent)keyReleased(KeyEvent)

Page 18: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

18

Some common events in Java GUI programming

Some common events in Java GUI programming

�With examples, we will illustrate some common events in Java GUI programming�Events caused by user’s actions:

�Action Events (Button)�Mouse Events (Mouse)�Key Events (Keyboard)

�Internal events (from Operation System)�Action Events (Timer)

Page 19: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

19

Handling action events:a JButtonexample

Handling action events:a JButtonexample

�Two buttons OKand Cancelin a window.�A message is displayed on the console to indicate

which button is clicked and at what time.

�Two buttons OKandCancelin a window.�A message is displayed on the console to indicate

which button is clicked and at what time. Run

public class TestActionEventextends JFrame{

// Create two buttons

private JButtonjbtOk= new JButton("OK");

private JButtonjbtCancel=new JButton("Cancel");

public TestActionEvent() {

getContentPane().setLayout(newFlowLayout());

// Add buttons to the frame

getContentPane().add(jbtOk);

getContentPane().add(jbtCancel);

// to be continued...

Page 20: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

20

// Create a listener object

ButtonListenerbtListener= new ButtonListener();

// Register listeners

jbtOk.addActionListener(btListener);

jbtCancel.addActionListener(btListener);

}

public static void main(String[] args) {

TestActionEventframe = new TestActionEvent();

...

}

}

class ButtonListenerimplements ActionListener{

/** This method will be invoked when a button is clicked */

public void actionPerformed(ActionEvente){

System.out.println("The" + e.getActionCommand() + " button is "

+ "clicked at\n " + new java.util.Date(e.getWhen()));

}

}

Event sourceEvent listener Event registration

Event handler, part of the event listener

Page 21: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

21

Handling action vvents: a Timer example

Handling action vvents: a Timer example

Thejavax.swing.Timerclass is a source component that automatically fires ActionEventsat a predefined rate.

javax.swing.Timer

+Timer(delay: int, listener:ActionListener)

+addActionListener(listener:ActionListener): void

+start(): void+stop(): void+setDelay(delay: int): void

Creates a Timer witha specified delay in milliseconds and anActionListener.

Adds an ActionListener to the timer.

Starts this timer.Stops this timer.Sets anew delay value for this timer.

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

Run

Page 22: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

22

public class AnimationDemoextends JFrame{

public AnimationDemo() {

// Create a MovingMessagePanelfor displaying a moving message

MovingMessagePanelp = new MovingMessagePanel("messagemoving?");

getContentPane().add(p);

// Create a timer for the listener p

Timer timer= new Timer(100, p);

timer.start();

}

public static void main(String[] args) {

AnimationDemoframe = new AnimationDemo();

...

}

}

class MovingMessagePanelextendsJPanelimplementsActionListener{

private String message = "Welcome to Java";

private intxCoordinate= 5; private intyCoordinate= 20;

//to be continued...

Page 23: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

23

public MovingMessagePanel(Stringmessage) {

this.message= message;

}

/** Handle ActionEvent*/

public void actionPerformed(ActionEvente){

repaint();

}

/** Paint message */

public void paintComponent(Graphicsg){

super.paintComponent(g);

if (xCoordinate> getWidth()) xCoordinate= -100;

xCoordinate+= 2;

g.drawString(message, xCoordinate, yCoordinate);

}

}

Page 24: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

24

Handling window events: an example

Handling window events: an example

�Different window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified.

�This program creates a frame, listens to the window events, and displays messages on the console to indicate events that are occurring.

�Different window events: window opened,closing,closed,activated,deactivated,iconified, and deiconified.

�This program creates a frame, listens to the window events, and displays messages on the console to indicate events that are occurring.

Run

Page 25: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

25

public class TestWindowEventextends JFrameimplements WindowListener{

public static void main(String[] args) {

TestWindowEventframe = new TestWindowEvent();

...

}

public TestWindowEvent() {

addWindowListener(this);// Register listener

}

/*MUST override all 7 methods:windowDeiconified, windowIconified,

windowActivated, windowDeactivated, windowOpened, windowClosing,

windowClosed*/

public void windowDeiconified(WindowEventevent) {

System.out.println("Windowdeiconified");

}

...

Event source and event listener are the same object

Page 26: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

26

Handling mouse events: class MouseEvent

Handling mouse events: class MouseEvent

java.awt.event.MouseEvent+getButton(): int+getClickCount(): int+getPoint(): java.awt.Point+getX(): int +getY(): int

Indicates which mouse buttonhas been clicked.Returns the number of mouse clicksassociated 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 ofthe mouse point.

java.awt.event.InputEvent+getWhen(): long+isAltDown(): boolean+isControlDown(): boolean+isMetaDown(): boolean+isShiftDown(): boolean

Returns the timestamp whenthis event occurred.Returns whether or notthe Alt modifier is down onthis event.Returns whether or notthe Control modifier is down onthis event.Returns whether or notthe Meta modifier is down on this eventReturns whether or notthe Shift modifier is down on this event.

Page 27: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

27

Handling mouse events: listeners Handling mouse events: listeners

�Java provides two listener interfaces, MouseListenerand MouseMotionListener, to handle mouse events.

�The MouseListenerlistens to actions such as when the mouse is pressed, released, clicked, entered, or exited.

�The MouseMotionListenerlistens to actions such as draggingor movingthe mouse.

�Java provides two listener interfaces, MouseListenerand MouseMotionListener, to handle mouse events.

�TheMouseListenerlistens to actions such as when the mouse is pressed,released,clicked,entered, or exited.

�TheMouseMotionListenerlistens to actions such as draggingormovingthe mouse.

Page 28: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

28

Handling mouse events: listeners (Cont’d)

Handling mouse events: listeners (Cont’d)

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 whenthe mouse button hasbeen pressed onthesource component.

Invoked whenthe mouse button hasbeenreleased onthesource component.

Invoked whenthe mouse button hasbeen clicked(pressedandreleased)on the sourcecomponent.

Invoked whenthe mouse enters the source component.Invoked whenthe mouse exitsthe source component.

java.awt.event.MouseMotionListener

+mouseDragged(e: MouseEvent): void+mouseMoved(e: MouseEvent): void

Invoked whena mouseis moved witha button pressed.Invoked whena mouseis moved withouta button pressed.

Page 29: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

29

Handling mouse events: a moving message example

Handling mouse events: a moving message example

Display a message in a panel. The message moves as the mouse is dragged and is always displayed at the mouse point.

Run

public class MoveMessageDemoextends JFrame{

public MoveMessageDemo() {

getContentPane().setLayout(newBorderLayout());

getContentPane().add(newMoveMessagePanel("Welcometo Java"));

}

public static void main(String[] args) {

MoveMessageDemoframe = new MoveMessageDemo();

...

}

}// to be continued...

Page 30: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

30

class MoveMessagePanelextendsJPanelimplementsMouseMotionListener{

private String message = "Welcome to Java";

private intx = 20; private inty = 20;

public MoveMessagePanel(Strings) {

message = s;

addMouseMotionListener(this);

}

protected void paintComponent(Graphicsg){

super.paintComponent(g);

g.drawString(message, x, y);

}

public void mouseDragged(MouseEvente){

x = e.getX();

y = e.getY();

repaint();

}

public void mouseMoved(MouseEvente){}

}

Page 31: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

31

Handling keyboard events: listener and handlers

Handling keyboard events: listener and handlers

�To process a keyboard event, use the handlers in the KeyListenerinterface:�keyPressed(KeyEvente)-called when a key is pressed�keyReleased(KeyEvente)-called when a key is

released�keyTyped(KeyEvente)-called when a key is pressed

and then released

�To process a keyboard event, use the handlers in theKeyListenerinterface:�keyPressed(KeyEvente)-called when a key is pressed�keyReleased(KeyEvente)-called when a key is

released�keyTyped(KeyEvente)-called when a key is pressed

and then released

Page 32: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

32

Handling keyboard events: class KeyEvent

Handling keyboard events: class KeyEvent

�Methods:

getKeyChar()method

getKeyCode()method

�Methods:

getKeyChar()method

getKeyCode()method

�Keys:HomeVK_HOMEEndVK_EndPage UpVK_PGUPPage DownVK_PGDNUpVK_UPDownVK_DOWNLeftVK_LEFTRightVK_RIGHT

�Keys:HomeVK_HOMEEndVK_EndPage UpVK_PGUPPage DownVK_PGDNUpVK_UPDownVK_DOWNLeftVK_LEFTRightVK_RIGHT java.awt.event.KeyEvent

+getKeyChar(): char+getKeyCode(): int

Returnsthe characterassociated with thekey.Returns the integer keyCode associatedwith the key.

java.awt.event.InputEvent

Page 33: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

33

Handling keyboard events:an example

Handling keyboard events:an example

Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys.

Run

public class KeyboardEventDemoextends JFrame{

private KeyboardPanelkeyboardPanel=new KeyboardPanel();

public KeyboardEventDemo() {

getContentPane().add(keyboardPanel);//create UI

keyboardPanel.setFocusable(true);//set focus

}

public static void main(String[] args) {

KeyboardEventDemoframe = new KeyboardEventDemo();

...

}

}// to be continued...

Page 34: Event-driven Programming with the Java Event Model...6 General structure of event-driven General structure of event-driven programming programming1. Start off by setting up its internal

34

class KeyboardPanelextendsJPanelimplementsKeyListener{

private intx=100; private inty=100; private char keyChar=‘A’;

public KeyboardPanel() { addKeyListener(this);}

protected void paintComponent(Graphicsg){

super.paintComponent(g);

g.drawString(String.valueOf(keyChar), x, y);

}

public void keyPressed(KeyEvente){

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 keyReleasedandkeyTyped

}