14slide_2007 - Chapter 14 Event-Driven Programming Event...

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: Chapter 14 Event-Driven Programming Event EE3206/EE5805 Java Programming & Applications 1 Objectives To start with event-driven programming with a simple example. To To explain the concept of event-driven programming. To 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. To To write programs to deal with MouseEvent. To To understand the use of Adpaters. To To write programs to deal with KeyEvent. To To use the Timer class to control animations. To EE3206/EE5805 Java Programming & Applications 2 Procedural vs. Event-Driven Programming Procedural programming is executed in Procedural procedural order. In event-driven programming, code is executed In upon activation of events. EE3206/EE5805 Java Programming & Applications 3 Taste of Event-Driven Programming The example displays a button in the frame. A The 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 An event the program that something has happened. The event is generated/fired by external user The actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer. EE3206/EE5805 Java Programming & Applications 5 Event Classes ActionEvent AdjustmentEvent EventObject AWTEvent ComponentEvent ItemEvent TextEvent ContainerEvent FocusEvent InputEvent PaintEvent WindowEvent KeyEvent MouseEvent ListSelectionEvent The above is the events that can be generated by external action. EE3206/EE5805 Java Programming & Applications 6 Event Information An event object contains whatever properties are relevant An to the event. You can identify the source object of the event using the You getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of The events, such as button actions, window events, component events, mouse movements, and keystrokes. EE3206/EE5805 Java Programming & Applications 7 Selected 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. JButton JCheckBox JRadioButton JTextField JComboBox Window Component Component ActionEvent ItemEvent, ActionEvent ItemEvent, ActionEvent ActionEvent ItemEvent, ActionEvent WindowEvent MouseEvent KeyEvent Fire EE3206/EE5805 Java Programming & Applications 8 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) ActionListener +actionPerformed(event: ActionEvent) Register by invoking source.addActionListener(listener); listener: CustomListenerClass (b) A JButton source component with an ActionListener EE3206/EE5805 Java Programming & Applications 9 The Delegation Model: Example JButton jbt = new JButton("OK"); ActionListener listener = new OKListener(); 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 10 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 11 java.awt.event.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 12 Inner Classes Listener A listener class is designed specifically to create a listener object for a GUI listener component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class. Inner class: A class is a member of another class. 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 An in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class. ShowInnerClass EE3206/EE5805 Java Programming & Applications 13 Inner Classes 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(); } } // OuterClass.java: 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 14 Inner Classes (cont.) Inner classes can make programs simple and concise. Inner An inner class supports the work of its containing outer An class and is compiled into a class named OuterClassName$InnerClassName.class. For example, the OuterClassName inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class. OuterClass An inner class can be declared public, protected, or private An subject to the same visibility rules applied to a member of the class. An inner class can be declared static. A static inner class An can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class EE3206/EE5805 Java Programming & Applications 15 Revising SimpleEventDemo Using Inner Classes SimpleEventDemoInnerClass Run EE3206/EE5805 Java Programming & Applications 16 Anonymous Inner Classes An anonymous inner class must always extend a superclass or An implement an interface, but it cannot have an explicit extends or implements clause. An anonymous inner class must implement all the abstract An methods in the superclass or in the interface (so that can be instantiated). An anonymous inner class always uses the no-arg constructor An from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). An anonymous inner class is compiled into a class named An OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class. EE3206/EE5805 Java Programming & Applications 17 Anonymous Inner Classes (cont.) Inner class listeners can be shortened using anonymous Inner inner classes. An anonymous inner class is an inner class without a name. An anonymous It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary } EE3206/EE5805 Java Programming & Applications 18 Revising SimpleEventDemo Using Anonymous Inner Classes SimpleEventDemoAnonymousInnerClass Run EE3206/EE5805 Java Programming & Applications 19 Example: Handling Simple Action Events Objective: Display two buttons OK and Cancel in the Objective: two OK Cancel 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 20 Interaction Between Source and Listener • Let say a custom class ButtonListener implements ActionListener in the following example: jbtOK registers btListener by invoking addActionListener(btListner). jbtCancel registers btListener by invoking addActionListener(btListner). jbtOK invokes btListener’s actionPerformed method to process an ActionEvnet. jbtCancel invokes btListener’s actionPerformed method to process an ActionEvent. : TestActionEvent jbtOK: JButton jbtCancel: JButton btListener: ButtonListener 1. 2. 3. 4. 1. addActionListener 2. addActionListener 3. actionPerformed 4. actionPerformed EE3206/EE5805 Java Programming & Applications 21 Example: Handling Window Events 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 22 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 EE3206/EE5805 Java Programming & Applications 23 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 24 Handling Mouse Events Java provides two listener interfaces, Java MouseListener and MouseMotionListener, MouseListener to handle mouse events. to The MouseListener listens for actions such as The MouseListener when the mouse is pressed, released, entered, exited, or clicked. The MouseMotionListener listens for The MouseMotionListener actions such as dragging or moving the mouse. EE3206/EE5805 Java Programming & Applications 25 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 26 Adapters There are only one abstract method in ActionListener for There handling ActionEvent There are many abstract methods in There MouseListener/MouseMotionListener interfaces Inconvenient to implement all methods everytime, even you do not need Inconvenient some of the handler. Java API provides some Adpaters which are abstract classes with empty Java implementation of the corresponding interface methods. Custom listener extends the adapter and override the empty handle on Custom demand. Example: Example: public abstract class MouseAdapter MouseAdapter implements MouseListener, MouseMotionListener EE3206/EE5805 Java Programming & Applications 27 Example: Moving Message Using Mouse Objective: Create a program to display a message in a panel. 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 28 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 Called when a key is released. Called keyTyped(KeyEvent e) keyTyped(KeyEvent Called when a key is pressed and then released. Adapter Adapter public abstract class KeyAdapter KeyAdapter implements KeyListener EE3206/EE5805 Java Programming & Applications 29 The KeyEvent Class KeyEvent Methods: Methods: getKeyChar() method getKeyCode() method 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 30 Example: Keyboard Events Demo Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys. KeyEventDemo Run EE3206/EE5805 Java Programming & Applications 31 The Timer Class Some non-GUI components can fire events. The javax.swing.Timer class is a source component that fires an ActionEvent at 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 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 The use it to display a moving message. AnimationDemo Run EE3206/EE5805 Java Programming & Applications 32 ...
View Full Document

Ask a homework question - tutors are online