Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Event-Driven Programming Reading: Chapter 16 (except 16.5) 1 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Motivations Suppose you write a GUI program in which the user enters the loan amount, annual interest rate, and number of years click the Compute Loan button to obtain the monthly payment and t t l paymentt total How do you accomplish the task? You have to use event-driven programming to write the code to respond to the button-clicking event. 2 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Motivations Suppose you wish to write a program that animates a rising flag How do yyou accomplish p the task? One way is to use a timer in event-driven programming 3 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Objectives To describe events, event sources, and event classes (§16.2) To define listener classes, register listener objects with the source object, and write the code to handle events (§16.3) To define listener classes using inner classes (§16.4) To get input from text field upon clicking a button (§16.7) To write programs to deal with WindowEvent (§16.8) MouseEvent (§16.10) KeyEvent (§16.11) To simplify p y codingg for listener classes usingg listener interface adapters (§16.9) To use the Timer class to control animations (§16.12) 4 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Procedural vs. Event-Driven Programming Procedural programming is executed in procedural order. In event-driven programming, code is executed upon activation of events Example – button click Webb interfaces W i f are essentially i ll event-driven programming, usually written in JavaScript 5 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Events An event can be defined as a type of signal to the program that something has happened. The event is ggenerated byy external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer The program can respond to or ignore an event 6 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Event Classes An event is an instance of an event class Sub-classes of EventObject deal with ith special i l ttypes off events, t suchh as button actions EventObject AWTEvent ActionEvent ContainerEvent AdjustmentEvent FocusEvent ComponentEvent InputEvent ItemEvent PaintEvent TextEvent WindowEvent MouseEvent KeyEvent ListSelectionEvent ChangeEvent 7 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Selected User Actions You can identify the source object of the event using the getSource() instance method in the EventObject class Selected User Actions Source Object Event Type Generated Click a button JButton ActionEvent Click a check box JCheckBox ItemEvent, ActionEvent Click a radio button JRadioButton ItemEvent, ActionEvent Press return on a text field JTextField ActionEvent Select a new item JComboBox ItemEvent, ActionEvent Window opened, closed, etc. Window WindowEvent Mouse pressed, released, etc. Component MouseEvent Key released, pressed, etc. Component KeyEvent Subclasses inherit the ability to fire events – e.g., all subclasses of Component can fire MouseEvent, KeyEvent, etc. 8 (c) 2011 Pearson Education, Inc. & Robert F. Kelly The Delegation Model A source object fires an event and a listener handles it Text UML notation is nonstandard (and possibly incomplete). This is likely a non-exclusive association Trigger an event User Action source: SourceClass XListener +addXListener(listener: XListener) +handler(event: XEvent) Register by invoking source.addXListener(listener); (a) A generic source component with a generic listener listener: ListenerClass sou rce: J Button B tt Acti on List ener +addActionListener(l istener: Act ionListener) (b) A JButton source component with an Act ionListener 9 +acti onPerfor med(event: ActionEvent) Register by invoking source.addActi onListen er(li stener); lis tener: CustomLi stenerClass ActionListener interface defines an actionPerformed method (c) 2011 Pearson Education, Inc. & Robert F. Kelly Listener Interfaces Java provides a listener interface for every type of event Notice the naming: e.g., ActionListener is associated with ActionEvent Listener interface methods are referred to as handlers 10 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Source Component Internals Diagram on left shows general case JButton example in diagram on right source: SourceClass source: JButton +addXListener(XListener listener) An event is triggered event: XEvent Invoke listener1.handler(event) listener2 handler(event) listener2.handler(event) … listenern.handler(event) +addActionListener(ActionListener listener) Keep it a list An event is triggered listener1 listener2 … li t listenern event: ActionEvent (a) Internal function of a generic source object Keep it a list Invoke listener1.actionPerformed(event) listener2 actionPerformed(event) listener2.actionPerformed(event) … listenern.actionPerformed(event) listener1 listener2 … li t listenern (b) Internal function of a JButton object An event causes the actionPerformed method of all registered listeners to be invoked 11 (c) 2011 Pearson Education, Inc. & Robert F. Kelly The Delegation Model: Example Textbook illustrates listeners with the code below JButton jbt = new JButton( JButton("OK"); OK ); ActionListener listener = new OKListener(); jbt.addActionListener(listener); More often, you just have some class you are using implement the listener interface and then JButton jbt = new JButton("OK"); jb jbt.addActionListener(this); dd i i ( hi ) 12 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers) ActionEvent ItemEvent WindowEvent ActionListener ItemListener WindowListener ContainerEvent ContainerListener MouseEvent MouseListener KeyEvent KeyListener 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) 13 (c) 2011 Pearson Education, Inc. & Robert F. Kelly java.awt.event.ActionEvent A high-level event generated by a component (such as a Button) when the component-specific action occurs (such as being pressed) java.util.EventObject java.ut . ve tObject +getSource(): Object Returns the object on which the event initially occurred. java.awt.event.AWTEvent java.awt.event.ActionEvent +getActionCommand(): getActionCommand(): String Returns the command string associated with this action. For a button, its text is the command string. +getModifiers(): int Returns the modifier keys held down during this action event. +getWhen(): long Returns the timestamp when this event occurred. The time is the number of milliseconds since January 1, 1970, 00:00:00 GMT. 14 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Example: ControlCircle2 Program uses two buttons to control the size of a circle Pressing the “Enlarge” button causes events that increase the size of the circle 15 (c) 2011 Pearson Education, Inc. & Robert F. Kelly ControlCircle2.java … public class ControlCircle2 extends JFrame { private JButton jbtEnlarge = new JButton("Enlarge"); private JButton jbtShrink = new JButton("Shrink"); private CirclePanel canvas = new CirclePanel(); public ControlCircle2() { JPanel panel = new JPanel(); // panel groups buttons panel.add(jbtEnlarge); panel.add(jbtShrink); this.add(canvas, BorderLayout.CENTER); thi this.add(panel, dd( l BorderLayout.SOUTH); B d L t SOUTH) jbtEnlarge.addActionListener(new Listener()); jbtShrink.addActionListener(new Listener()); } 16 (c) 2011 Pearson Education, Inc. & Robert F. Kelly … ControlCircle2.java … class CirclePanel extends JPanel { private int radius = 5; // Default circle radius public void enlarge() { Calls C ll tto enlarge l andd shrink hi k change the radius of the circle radius++; repaint(); } public void shrink() { radius--; repaint(); } We have not covered this in class, but it is not essential to understand this program protected t t d void id paintComponent(Graphics i tC t(G hi g) ) { super.paintComponent(g); g.drawOval(getWidth() / 2 - radius, getHeight() / 2 radius, 2 * radius, 2 * radius); } 17 } (c) 2011 Pearson Education, Inc. & Robert F. Kelly … ControlCircle2.java … public static void main(String[] args) { JFrame frame = new ControlCircle2(); frame.setTitle("ControlCircle2"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); } 18 (c) 2011 Pearson Education, Inc. & Robert F. Kelly … ControlCircle2.java class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(new java.util.Date(e.getWhen())); if (e.getSource() == jbtEnlarge) canvas.enlarge(); else if (e.getSource() == jbtShrink) canvas.shrink(); } } Note that it is not good code to instantiate two anonymous Listener objects Alternate approach (not recommended by Liang) is to have ControlCircle2 implement ActionListener and then register the listener with: jbtEnlarge.addActionListener(this); 19 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Multiple Classes per File Notice in the ControlCircle2 example, the ControlCirle2.java file contained ControlCircle2, Listener, and CirclePanel classes Listener and CirclePanel classes are contained within the ControlCircle2 class Initially, Java allowed multiple classes in a file (if at most one was public) because it was convenient to include some helper classes in the same file with a larger class Later versions of Java allowed classes to be contained within other classes (inner classes) 20 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Inner Classes Inner class: A class is a member of another class Advantages: g In some applications, pp , yyou can use an inner class to make programs simple An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class 21 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Inner Class Features Inner class can reference the data and methods defined in the 22 outer class I Inner class l can bbe defined d fi d static t ti Objects in the inner class are often created in the outer class Reduces the number of source files Compiled into a class named OuterClassName$InnerClassName ControlCircle2 as it appears in the classes directory (c) 2011 Pearson Education, Inc. & Robert F. Kelly Inner Class Structure // OuterClass.java: inner class demo public class OuterClass { private int data; public class Test { ... } /** A method in the outer class */ / / public void m() { // Do something } public class A { ... } (a) 2 classes in a file // 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(); } } public class Test { ... // Inner class public class A { ... } } } (b) Class with inner class 23 (c) (c) 2011 Pearson Education, Inc. & Robert F. Kelly Window Events Previously, we examined action events Now we look at window events Any subclass of Window can fire: Window opened Window closing Window closed Window activated Window deactivated Window iconified Window deiconified 24 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Example TestWindowEvent.java When a window event occurs, a message is written to the console 25 (c) 2011 Pearson Education, Inc. & Robert F. Kelly TestWindowEvent … public class TestWindowEvent extends JFrame { public static void main(String[] args) { TestWindowEvent frame = new TestWindowEvent(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("TestWindowEvent"); frame.setSize(220, 80); frame.setVisible(true); } 26 (c) 2011 Pearson Education, Inc. & Robert F. Kelly … TestWindowEvent Anonymous class listener public TestWindowEvent() { addWindowListener(new WindowListener() { public void windowActivated(WindowEvent event) { System.out.println("Window activated"); } public void windowDeactivated(WindowEvent event) { System.out.println("Window deactivated"); } public void windowOpened(WindowEvent event) { System.out.println("Window opened"); } ... }); } } 27 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Listener Interface Adapters Methods in WindowsListener are abstract You must implement all the methods to satisfy the interface ((even th thoughh you might i ht nott needd some)) Convenience adapters provide default implementations of all the methods in the interface Example –WindowAdapter class implements all the methods for WindowListener Instantiate the adapter and override the methods you need 28 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Mouse Events Mouse event is fired when a mouse is Pressed Released R l d Clicked Moved Dragged on a component Mouse event object captures the event (e.g., location) MouseListener handles mouse events 29 (c) 2011 Pearson Education, Inc. & Robert F. Kelly MouseEvent java.awt.event.InputEvent +getWhen(): long Returns the timestamp when this event occurred. +isAltDo n(): boolean +isAltDown(): R t Returns whether h th or nott the th Alt modifier difi is i down d on this thi event. t +isControlDown(): boolean Returns whether or not the Control modifier is down on this event. +isMetaDown(): boolean Returns whether or not the Meta modifier is down on this event +isShiftDown(): boolean Returns whether or not the Shift modifier is down on this event. java.awt.event.MouseEvent +getButton(): int Indicates which mouse button has been clicked. + Cli kC +getClickCount(): () int i R Returns the h number b off mouse clicks li k associated i d with i h this hi event. +getPoint(): java.awt.Point Returns a Point object containing the x and y coordinates. +getX(): int Returns the x-coordinate of the mouse point. +getY(): int Returns the y-coordinate of the mouse point. 30 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Handling Mouse Events Java provides two listener interfaces, MouseListener and MouseMotionListener, to handle mouse events The MouseListener listens for actions such as when the mouse is pressed, released, entered, exited, or clicked The MouseMotionListener listens for actions such as dragging or moving the mouse 31 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Handling Mouse Events java.awt.event.MouseListener +mousePressed(e: MouseEvent): void Invoked when the mouse button has been pressed on the source component. +mouseReleased(e: MouseEvent): void Invoked when the mouse button has been released on the source component. +mouseClicked(e: MouseEvent): void Invoked when the mouse button has been clicked (pressed and released) on the source component. +mouseEntered(e: MouseEvent): void Invoked when the mouse enters the source component. +mouseExited(e: MouseEvent): void Invoked when the mouse exits the source component. java.awt.event.MouseMotionListener +mouseDragged(e: MouseEvent): void Invoked when a mouse button is moved with a button pressed. +mouseMoved(e: MouseEvent): void Invoked when a mouse button is moved without a button pressed. 32 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Example: Moving Text Using Mouse Objective: Create a program to display a message in a panel. And use the mouse to move the message The message moves as the mouse drags and is always displayed at the mouse point. 33 (c) 2011 Pearson Education, Inc. & Robert F. Kelly MoveMessageDemo … public class MoveMessageDemo extends JFrame { public MoveMessageDemo() { MovableMessagePanel p = new MovableMessagePanel( MovableMessagePanel("Welcome Welcome to Java"); Java ); setLayout(new BorderLayout()); add(p); } public static void main(String[] args) { MoveMessageDemo frame = new MoveMessageDemo(); frame.setTitle("MoveMessageDemo"); frame.setTitle( MoveMessageDemo ); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 100); frame.setVisible(true); } 34 (c) 2011 Pearson Education, Inc. & Robert F. Kelly … MoveMessageDemo public MovableMessagePanel(String s) { message = s; addMouseMotionListener(new MouseMotionAdapter() { / /** Handle mouse dragged event */ / public void mouseDragged(MouseEvent e) { // Get the new location and repaint the screen x = e.getX(); y = e.getY(); repaint(); }});} protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, x, y); }}} 35 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Handling Keyboard Events keyPressed(KeyEvent e) - keyReleased(KeyEvent y ( y e) ) - keyTyped(KeyEvent e) - Called when a key is pressed Called when a keyy is released Called when a key is pressed and then released. Similar to other event handling approaches 36 (c) 2011 Pearson Education, Inc. & Robert F. Kelly 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 d f d rate. javax.swing.Timer +Timer(delay: int, listener: ActionListener) Creates a Timer with a specified delay in milliseconds and an ActionListener. +addActionListener(listener: ActionListener): void +start(): void Adds an ActionListener to the timer. +stop(): void Stops this timer. +setDelay(delay: int): void Sets a new delay d l value l for f this hi timer. i Starts this timer. The Timer class can be used to control animations. For example, you can use it to display a moving message. 37 (c) 2011 Pearson Education, Inc. & Robert F. Kelly Timer Example: Clock Animation Chapter 15 includes code for a StillClock to show the current time, but the clock does not tick after it is displayed This h example l uses a Timer to animate the h clock l k 38 (c) 2011 Pearson Education, Inc. & Robert F. Kelly ClockAnimation StillClock draws a clock with the current time public class ClockAnimation extends JFrame { private StillClock clock = new StillClock(); public ClockAnimation() { add(clock); Timer timer = new Timer(1000, new TimerListener()); timer.start(); } private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { clock.setCurrentTime(); clock.repaint(); } } public static void main(String[] args) { JFrame frame = new ClockAnimation(); frame.setTitle("ClockAnimation"); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } 39 } (c) 2011 Pearson Education, Inc. & Robert F. Kelly Have You Satisfied the Objectives To describe events, event sources, and event classes (§16.2) To define listener classes, register listener objects with the source object, and write the code to handle events (§16.3) To define listener classes using inner classes (§16.4) To get input from text field upon clicking a button (§16.7) To write programs to deal with WindowEvent (§16.8) MouseEvent (§16.10) KeyEvent (§16.11) To simplify p y codingg for listener classes usingg listener interface adapters (§16.9) To use the Timer class to control animations (§16.12) 40 (c) 2011 Pearson Education, Inc. & Robert F. Kelly