slide4.3_2009 - Module 4.3 Module Event-Driven Programming...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 4.3 Module Event-Driven Programming Event EE3206/EE5805 Java Programming & Applications 1 Intended Learning Outcomes To start with event-driven programming with a simple example. To driven To explain the concept of event-driven programming. To driven To understand events, event sources, and event classes. To To declare listener classes and write the code to handle events. To To register listener objects in the source object. To To understand how an event is handled. To To write programs to deal with ActionEvent. ActionEvent To write programs to deal with MouseEvent. MouseEvent To understand the use of Adpaters. Adpaters To write programs to deal with KeyEvent. KeyEvent To use the Timer class to control animations. Timer EE3206/EE5805 Java Programming & Applications 2 Procedural vs. Event-Driven Driven Programming Programming Procedural programming is executed in procedural order. procedural In event-driven programming, code is executed In driven upon activation of events. upon EE3206/EE5805 Java Programming & Applications 3 Example of Event-Driven Driven Programming Programming The example displays a button in the frame. A message is displayed on the console when a button is clicked. SimpleEventDemo Run EE3206/EE5805 Java Programming & Applications 4 Events An event can be defined as a type of signal to event can the program that something has happened. The event is generated/fired by external user actions such as mouse movements, mouse mouse clicks, and keystrokes, or by the operating clicks and keystrokes or system, such as a timer. timer EE3206/EE5805 Java Programming & Applications 5 Event Information An event object contains whatever properties are relevant to the An event. event. You can identify the source object of the event using the getSource() identify of getSource iinstance method in the EventObject class. nstance EventObject class. The subclasses of EventObject deal with special types of events, EventObject deal such as button actions, window events, component events, mouse movements, and keystrokes. EE3206/EE5805 Java Programming & Applications 6 Common User Actions Table below lists external user actions, source objects, and event types generated. Source Object Event Type Generated User Action Click a button Click a check box Click a radio button Press return on a text field Select a new item Window opened, closed, etc. Mouse pressed, released, etc. Key released, pressed, etc. Act On JButton JCheckBox JRadioButton JTextField JComboBox Window Component Component Fire ActionEvent ItemEvent, ActionEvent ItemEvent, ActionEvent ActionEvent ItemEvent, ActionEvent WindowEvent MouseEvent KeyEvent EE3206/EE5805 Java Programming & Applications 7 The Delegation 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 EE3206/EE5805 Java Programming & Applications 8 The Delegation Model: Example JButton jbt = new JButton("OK"); ActionListener listener = new CustomListenerClass(); jbt.addActionListener(listener); The internal function of a source component: The 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 9 EE3206/EE5805 Java Programming & Applications Selected Event Handlers Event Class ActionEvent ItemEvent WindowEvent Listener Interface ActionListener ItemListener WindowListener Listener Methods (Handlers) actionPerformed(ActionEvent) itemStateChanged(ItemEvent) windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) componentAdded(ContainerEvent) componentRemoved(ContainerEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) keyTypeed(KeyEvent) ContainerEvent MouseEvent ContainerListener MouseListener KeyEvent KeyListener Handled by EE3206/EE5805 Java Programming & Applications 10 ActionEvent java.util.EventObject +getSource(): Object Returns the object on which the event initially occurred. java.awt.event.AWTEvent java.awt.event.ActionEvent +getActionCommand(): String +getModifiers(): int +getWhen(): long Alt, Ctrl, Shift and Meta (Meta - on the SunTM keyboard) 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. The time is the number of milliseconds since January 1, 1970, 00:00:00 GMT. EE3206/EE5805 Java Programming & Applications 11 Inner Classes Listener A listener class is designed specifically to create a listener object for a GUI listener bject component (e.g., a button). It will not be shared by other applications. So, it component cations. is appropriate to define the listener class inside the frame class as an inner is ss class. class. Inner class: A class is a member of another class. Inner Advantages: In some applications, you can use an inner class to make programs simple. In An inner class can reference the data and methods defined in the outer class in An outer which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class. constructor EE3206/EE5805 Java Programming & Applications 12 Inner Classes Pseudo Code public class Test { ... } public class A { ... } (a) public class Test { ... // Inner class public class A { ... } } (b) } (c) // An inner class class InnerClass { /** A method in the inner class */ public void mi() { // Directly reference data and method // defined in its outer class data++; m(); } } // inner class demo public class OuterClass { private int data; /** A method in the outer class */ public void m() { // Do something } EE3206/EE5805 Java Programming & Applications 13 Inner Classes Inner classes can make programs simple and concise. An inner class supports the work of its containing outer class and is An nd compiled into a class named OuterClassName$InnerClassName.class. For OuterClassName For example, the inner class InnerClass iin OuterClass iis compiled into InnerClass n OuterClass s OuterClass$InnerClass.class. OuterClass An inner class can be declared public, protected, or private subject to public protected or private subject the same visibility rules applied to a member of the class. An inner class can be declared static, so that a static iinner class can be static so static nner accessed using the outer class name. E.g. OuterClassName.InnerClassName OuterClassName.InnerClassName A static iinner class cannot access nonstatic members of the outer class. static nner nonstatic SimpleEventDemoInnerClass Run EE3206/EE5805 Java Programming & Applications 14 Anonymous Inner Classes Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. name It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: An new SuperClassName/InterfaceName() { // Implement or override all methods in superclass or interface // Other methods if necessary } EE3206/EE5805 Java Programming & Applications 15 Anonymous Inner Classes An anonymous inner class must always extend a superclass or implement an interface, superclass but it cannot have an explicit extends or implements clause. extends or implements clause. An anonymous inner class must implement all the abstract methods iin the superclass or n implement superclass or in the interface (so that can be instantiated). in An anonymous inner class always uses the no-arg constructor from its superclass to uses from superclass to create an instance. If an anonymous inner class implements an interface, the constructor create terface, is Object(). Object() An anonymous inner class is compiled into a class named OuterClassName$n.class. For OuterClassName$ For example, if the outer class Test has two anonymous inner classes, these two classes are Test has compiled into Test$1.class and Test$2.class. Test$1.class and Test$2.class SimpleEventDemoAnonymousInnerClass Run EE3206/EE5805 Java Programming & Applications 16 Example: Example: Handling Simple Action Events Handling Objective: Display two buttons OK and Cancel in the OK and Cancel in window. A message is displayed on the console to indicate which button is clicked, when a button is clicked. TestActionEvent Run EE3206/EE5805 Java Programming & Applications 17 Example: Example: Handling Window Events Handling Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event. TestWindowEvent Run EE3206/EE5805 Java Programming & Applications 18 Example: Example: Multiple Listeners for a Single Source Objective: This example modifies TestActionEvent to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listener. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event. TestMultipleListener Run 19 EE3206/EE5805 Java Programming & Applications Handling Mouse Events Java provides two listener interfaces, two MouseListener and MouseMotionListener, MouseListener to handle mouse events. The MouseListener llistens for actions such as MouseListener istens when the mouse is pressed, released, entered, exited, or clicked. or The MouseMotionListener listens for MouseMotionListener actions such as dragging or moving the actions dragging mouse. mouse. EE3206/EE5805 Java Programming & Applications 20 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. EE3206/EE5805 Java Programming & Applications 21 Handling Mouse Events 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 button is moved with a button pressed. Invoked when a mouse button is moved without a button pressed. EE3206/EE5805 Java Programming & Applications 22 Adapters There are only one abstract method in ActionListener for ActionListener for handling ActionEvent ActionEvent However, there are many abstract methods in MouseListener/MouseMotionListener interfaces MouseListener/MouseMotionListener Inconvenient to implement all methods every time, even you do not need some of the handler. some Java API provides some Adpaters which are abstract classes with empty Adpaters which implementation of the corresponding interface methods. implementation E.g. MouseAdapter, MouseMotionAdapter MouseAdapter MouseMotionAdapter Custom listener extends the adapter and override the empty handle on override the demand. demand. In the Java API: In public abstract class MouseAdapter public MouseAdapter implements MouseListener, MouseMotionListener, MouseWheelListener implements MouseListener MouseMotionListener MouseWheelListener EE3206/EE5805 Java Programming & Applications 23 Example: Example: Moving Message Using Mouse Moving Objective: Create a program to display a message in a panel. program You can use the mouse to move the message. The message moves as the mouse drags and is always displayed at the mouse point. MoveMessageDemo Run EE3206/EE5805 Java Programming & Applications 24 Handling Keyboard Events To process a keyboard event, use the following handlers in the KeyListener interface: keyPressed(KeyEvent e) keyPressed(KeyEvent Called when a key is pressed. keyReleased(KeyEvent e) keyReleased(KeyEvent e) Called when a key is released. Called keyTyped(KeyEvent e) keyTyped(KeyEvent Called when a key is pressed and then released. Corresponding Adapter Corresponding public abstract class KeyAdapter public KeyAdapter implements KeyListener implements KeyListener EE3206/EE5805 Java Programming & Applications 25 The KeyEvent Class The KeyEvent Methods: Methods: getKeyChar() () getKeyCode() getKeyCode() Keys: Keys: Home End Page Up Page Down etc... VK_HOME VK_END VK_PGUP VK_PGDN java.awt.event.InputEvent java.awt.event.KeyEvent +getKeyChar(): char +getKeyCode(): int Defined as some constant values in the class Returns the character associated with the key in this event. Returns the integer keyCode associated with the key in this event. EE3206/EE5805 Java Programming & Applications 26 Example: Keyboard Events Demo Objective: Display a user-iinput character. The user nput can also move the character up, down, left, and right using the arrow keys. right KeyEventDemo Run EE3206/EE5805 Java Programming & Applications 27 The Timer Class The Some non-GUI components can fire events. The javax.swing.Timer class Some GUI javax.swing.Timer class is a source component that fires an ActionEvent at a predefined rate. ActionEvent 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 Timer class use it to display a moving message. use AnimationDemo Run EE3206/EE5805 Java Programming & Applications 28 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online