Quick intro to Event Driven Programming Dan Fleck George Mason University
What is Event Driven Programming When you want to know if some external entity (generally a person) does something you have two options Polling - repeatedly ask if it has occurred Event based - tell the event generator to let you know when it has occurred
Example A Button exists on a form, you want to know when the Button is pressed: Tell the button you want to know: redButton.addActionListener(myObj); Tells “redButton” that whenever the button is pressed, let “myObj” know. myObj is listening for button presses.
Example When the button is pressed, the method from the ActionListener interface is called on myObj (which must implement the interface). Then myObj can do what it wants to do whenever the button is pressed
Listener Pattern Important Your code implements the xxxListener interface (requiring you to have specific methods in your class) Your code calls someObject.addXxxListener(this) to register yourself “this” as a listener SomeObject adds you into a list of listeners When the event of interest happens, all listeners have one of their specific xxxListener interface methods called with the XXXEvent object. Important
Code Example public class DoSomething implements MouseMotionListener { private JPanel jp; public DoSomething() { jp = new JPanel(); jp.addMouseMotionListener(this); } // Specified in the MouseMotionListener interface public void mouseDragged(MouseEvent e) { System.out.printf (“Mouse dragged to location (%d, %d) “,e.getX(), e.getY()); public void mouseMoved(MouseEvent e) { System.out.printf (“Mouse moved to location (%d, %d) “,e.getX(), e.getY());
Code Example JPanel Class … public void addMouseMotionListener(MouseMotionListener m) { mouseMotionListeners.add(m); } // Called when something happens with the mouse private void fireMouseMotionEvent() { MouseMotionEvent mEvent = new MouseMotionEvent(x, y, …..); // Notify the listeners! for (MouseMotionListener m : mouseMotionListeners) { if (dragged) m.mouseDragged(mEvent); else m.mouseMoved(mEvent); } // NOTE: This is NOT really the code, but it is essentially the idea that is used in the real JVM code.
That’s it! Many types of listeners and Events are present in Java Usually these are from the User Interface classes (Buttons, panels, sliders, checkboxes, etc…).