Event-Driven Programming
Event-Driven Programming
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
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
11
Event registration
o Who is interested in what event with what type
o Here, the who object is called listener
12
13
Dispatching Events
mouse down (10,50)
Window
Panel
Button
Textbox
Panel
Button
Button
Dispatching Events
mouse down (10,50)
Window
Panel
Button
Textbox
Panel
Button
Button
Dispatching Events
mouse down (10,50)
Window
Panel
Button
Textbox
Panel
Button
Button
Dispatching Events
mouse down (10,50)
Window
Panel
Button
Textbox
Panel
Button
Button
Dispatching Events
mouse down (10,50)
Window
Panel
Button
Textbox
Panel
Button
Button
Implementing Listeners
Listener is an interface
o Overwrite abstract handler methods
19
Component-as-Listener
Component implements listener interface
o addXListener(this)
Inner Listener
Adapters
Predened do nothing listener class
o Handler methods empty
Separate Listener
Existing (or specialised) separate class
o Implement interface
o addXListener(listener)
Example: ShowEvent
o mouseTarget: inner listener
o keyTarget: inner listener, separate listener
o moveTarget: component-as-listener
Run
24
Source Object
JButton Window Component Component Component JCheckBox JRadioButton JTextField JComboBox
25
+handler(event: XEvent)
ActionListener
+actionPerformed(event: ActionEvent)
listener: CustomListenerClass
26
event: XEvent
event: ActionEvent
+handler(
+handler(
27
(new JButton("OK")).addActionListener(listener);
28
Listener Interface
ActionListener WindowListener
MouseEvent
MouseListener
Event Sources
Users actions:
o Action Events (BuKon)
o Mouse Events (Mouse)
o Key Events (Keyboard)
o Window Events (Interaction)
30
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
Run
// 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
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); } }
Run
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"); } ...
38
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
40
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
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
44
Returns the character associated with the key. Returns the integer keyCode associated with the key.
45
Run
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();
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
49
Next on Thursday
Java Applet
50