GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1
Agenda General event handling strategy Handling events with separate listeners Handling events by implementing interfaces Handling events with named inner classes Handling events with anonymous inner classes How to Write an Action Listener How to Write an Item Listener How to Write a Component Listener 2
GUIs and Event driven The structure of containers and components sets up the physical appearance of a GUI But it doesn t say anything about how the GUI behaves. What can the user do to the GUI and how will it respond? GUIs are largely event driven The program waits for events that are generated by the user s actions (or by some other cause) 3
Event Listeners When an event occurs, the program responds by executing an event handling method In order to program the behavior of a GUI, you have to write event handling methods to respond to the events that you are interested in The most common technique for handling events in Java is to use event listeners 4
A Listener A listener is an object that includes one or more event handling methods When an event is detected by another object, such as a button or menu, the listener object is notified and it responds by running the appropriate event handling method An event is detected or generated by an object The event itself is actually represented by a third object Another object, the listener, has the responsibility of 5 responding to the event
Components, Events, Listeners 2. Notify listener event click OK button 1. Detect/Generate event component listener ButtonHandler 0. Register 3. Perform some action (i.e, terminate the program) OK button 6
Example: Events and Listeners When the user clicks the OK button, an event is generated This event is represented by an object belonging to the class ActionEvent The event that is generated is associated with the button; we say that the button is the source of the event The listener object in this case is an object belonging to the class ButtonHandler, which is defined as a nested class inside 7 HelloWorldGUI3
ButtonHandler Demo private static class ButtonHandler implements ActionListener { public void actionperformed(actionevent e) { System.exit(0); } } public static void main(string[] args) {... ButtonHandler listener = new ButtonHandler(); // create listener object okbutton.addactionlistener(listener); // regiter.. } 8
General Strategy Determine what type of listener is of interest ActionListener, AdjustmentListener, etc. Define a class of that types Implement interface (KeyListener, etc.) Extend class (KeyAdapter, etc.) Register an object of your listener class with the window w.addxxxlistener(new MyListenerClass()); E.g., addkeylistener, addmouselistener 9
Handling Events with a Separate Listener: Simple Case Listener does not need to call any methods of the window to which it is attached 10
Separate Listener: Simple Case 11
Generalizing Simple Case What if ClickListener wants to draw a circle wherever mouse is clicked? Why can't it just call getgraphics to get a Graphics object with which to draw? General solution: Call event.getsource to obtain a reference to window or GUI component from which event is originated Cast result to type of interest Call methods on that reference 12
Handling Events with Separate Listener: General Case 13
Case 2: Implementing a Listener Interface 14
Adapters vs. Interfaces: Method Signature Errors What if you goof on the method signature? public void mousepressed(mouseevent e) public void mousepressed() Interfaces Compile time error Adapters No compile time error, but nothing happens at run time when you press the mouse Solution using @Override 15
Using @Override Solution for adapters (and overriding in Java 5 in general): @Override annotation Whenever you think you are overriding a method, put "@Override" on the line above the start of the method. If that method is not actually overriding an inherited method, you get a compile time error. 16
Using @Override Example 17
Case 3: Named Inner Classes 18
Case 4: Anonymous Inner Classes 19
Event Handling Strategies: Pros and Cons Separate Listener (Case 1) Advantages Can extend adapter and thus ignore unused methods Separate class easier to manage Disadvantage 20 Need extra step to call methods in main window
Event Handling Strategies: Pros and Cons Main window that implements interface (Case 2) Advantage No extra steps needed to call methods in main window Disadvantage Must implement methods you might not care about 21
Event Handling Strategies: Pros and Cons Named inner class (Case 3) 22
Event Handling Strategies: Pros and Cons Named inner class (Case 3) Advantages Can extend adapter and thus ignore unused methods No extra steps needed to call methods in main window Disadvantage A bit harder to understand 23
Event Handling Strategies: Pros and Cons Anonymous inner class (Case 4) 24
Event Handling Strategies: Pros and Cons Anonymous inner class (Case 4) Advantages Same as named inner classes Even shorter Disadvantage Much harder to understand 25
Standard AWT Event Listeners 26
Getting Event Information: Event Objects Every event listener method has a single argument An object that inherits from the EventObject class The EventObject class defines one very useful method: Object getsource() Returns the object that fired the event You can query a MouseEvent object for information about where the event occurred, how many clicks the user made, which modifier keys were pressed, etc 27
Concepts: Low Level Events and Semantic Events Events can be divided into two groups: low level events and semantic events Low level events represent window system occurrences or low level input Examples: mouse and key events Everything else is a semantic event Examples: action and item events 28
Semantic Events are Preferable Whenever possible, you should listen for semantic events rather than low level event That way, you can make your code as robust and portable as possible Example: Listening for action events on buttons, rather than mouse events The button will react appropriately when the user tries to activate the button using a keyboard alternative or a look and feel specific gesture 29
Event Adapters To help you avoid implementing empty method bodies in the class that implements interface listener Java API generally includes an adapter class for each listener interface with more than one method Example: MouseAdapter which you can extend instead of implementing MouseListener 30
Inner Classes and Anonymous Inner Classes What if you want to use an adapter class, but do not want your public class to inherit from an adapter class? For example, suppose you write an applet, and you want your Applet subclass to contain some code to handle mouse events Since the Java language does not permit multiple inheritance, your class cannot extend both the Applet and MouseAdapter classes 31
Inner Classes and Anonymous Inner Classes A solution is to define an inner class A class inside of your Applet subclass A class that extends the MouseAdapter class Inner classes can also be useful for event listeners that implement one or more interfaces directly The more classes you create, the longer your program takes to start up and the more memory it will take 32
Listeners Supported by Swing Components component listener focus listener Listens for changes in the component's size, position, or visibility Listens for whether the component gained or lost the keyboard focus key listener Listens for key presses; key events are fired only by the component that has the current keyboard focus. 33
Listeners Supported by Swing Components mouse listener mouse motion listener Listens for mouse clicks, mouse presses, mouse releases and mouse movement into or out of the component's drawing area. Listens for changes in the mouse cursor's position over the component. mouse wheel listener Listens for mouse wheel movement over the component. 34
Listeners Codes Examples How to write an action listener How to write an item listener How to write a component listener 35
How to Write an Action Listener Action listeners are probably the easiest and most common event handlers to implement You implement an action listener to define what should be done when an user performs certain operation. An action event occurs, whenever an action is performed by the user Examples When the user clicks a button, chooses a menu36 item, and presses Enter in a text field
Steps for Implementing Action Listener 1. Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. 2. Register an instance of the event handler class as a listener on one or more components. public class MyClass implements ActionListener { somecomponent.addactionlistener(instanceofmyclass); 3. Include code that implements the methods in listener interface. public void actionperformed(actionevent e) {...//code that reacts to the action... } 37
ActionListenerDemo (1/2) 38
ActionListenerDemo (2/2) 39
Create a GUI Class for Reuse Create the GUI class as a subclass of JFrame Declare instance methods Can use all methods of JFrame Each object or each class instance than can have its own version of method. Declare attributes in the class scope not in the method scope In main method Create the object of that GUI class 40
JTextFieldDemoV2 (1/2) 41
JTextFieldDemoV2 (2/2) 42
A Similar But Larger Form Want to add the label and text field for lastname Want to add the label and text for for Want to add the button Cancel Thus, develop JTextFieldDemoV3 which is the subclass of JTextFieldDemoV2 Override methods in JTextFieldDemoV2 to add more components 43
JTextFieldDemoV3 (1/2) 44
JTextFieldDemoV3 (2/2) 45
JTextFieldDemoV4 Introduction Want to add action in GUI Make the class implement a listener, such as ActionListener Implement all required methods in the listener, such as need to implement public void actionperformed(actionevent e) {} in the class that imeplements ActionListener Register the listener to be notified when the component fires an event Example: submitbutton.addactionlistener(this) 46
JTextFieldDemoV4 47
Methods in JTextComponent String txtcomp.gettext(); returns the string value of the text component void comp.settext(string s); sets the string value of the text component void comp.setcaretposition(int position); sets the caret appears at the specified position Caret is the cursor indicating the insertion point in a text component 48
JTextAreaDemoV2 49
JTextAreaDemoV3 50
JTextAreaDemoV3 Output 51
How to Write an Item Listener Item events are fired by components that implement the ItemSelectable interface Generally, ItemSelectable components maintain on/off state for one or more items The Swing components that fire item events include buttons like check boxes, check menu items, toggle buttons etc...and combo boxes 52
ItemListener API void itemstatechanged(itemevent e) Invoked when an item has been selected or deselected by the user The code written for this method performs the operations that need to occur when an item is selected (or deselected) 53
ItemEvent Class Object getitem() Returns the component specific object associated with the item whose state changed Often this is a String containing the text on the selected item ItemSelectable getitemselectable() Returns the component that fired the item event. You can use this instead of the getsource method. 54
ItemEvent Class int getstatechange() Returns the new state of the item The ItemEvent class defines two states: SELECTED and DESELECTED 55
JCheckBoxDemoV2 56
JCheckBoxDemoV3 (1/2) 57
JCheckBoxDemoV3 (2/2) 58
JCheckBoxDemoV3 Output 59
Enabling Keyboard Operation Menus support two kinds of keyboard alternatives: mnemonics and accelerators Mnemonics offer a way to use the keyboard to navigate the menu hierarchy, increasing the accessibility of programs Accelerators, on the other hand, offer keyboard shortcuts to bypass navigating the menu hierarchy Mnemonics are for all users; accelerators are for power users. 60
A mnemonic A mnemonic is a key that makes an already visible menu item be chosen A menu item generally displays its mnemonic by underlining the first occurrence of the mnemonic character in the menu item's text You can specify a mnemonic either when constructing the menu item or with the setmnemonic method openmenuitem.setmnemonic(keyevent.vk_o); 61
An accelerator An accelerator is a key combination that causes a menu item to be chosen, whether or not it's visible To specify an accelerator, use the setaccelerator method openmenuitem.setaccelerator(keystroke.getkeystr oke(keyevent.vk_o, ActionEvent.CTRL_MASK)); 62
JMenuLookDemoV2 (1/3) 63
JMenuLookDemoV2 (2/3) 64
JMenuLookDemoV3 (1/3) 65
JMenuLookDemoV3 (2/3) 66
JMenuLookDemoV3 (3/3) 67
Setting mnemonic keys Using setmnemonic method and register action listener Use mnemonic key sequences as ALT F and O to access the menu item menu.setmnemonic(keyevent.vk_f); menu.addactionlistener(this); openmenuitem.setmnemonic(keyevent.vk_o); openmenuitem.addactionlistener(this); menu.add(openmenuitem); 68
Setting accelerator key Using setaccelerator method and add action listener to the menu item if it has not been added yet Use Ctrl O to use this menu ite openmenuitem.setaccelerator(keystroke.getkeystr oke(keyevent.vk_o, ActionEvent.CTRL_MASK)); 69
Handling Radio or CheckBox Menus Register ItemListener with the menuitem rb1.additemlistener(this); Implement method itemstatechanged(itemevent e) JMenuItem source = (JMenuItem) e.getsource(); if (e.getstatechange() == ItemEvent.SELECTED) { String s = "Your file type is " + source.gettext(); output.append(s + newline); output.setcaretposition( output.getdocument().getlength()); 70
How to Write a Component Listener The Component listener is a listener interface for receiving component events A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user Some of the examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. 71
The Listener Object The class that is interested in processing a component event either Implements the component listener interface and all the methods it contains or Extends the abstract ComponentAdapter class overriding only the methods of interest The listener object created from that class is then registered with a component using the component's addcomponentlistener method. 72
Component Events When the component's size, location, or visibility changes, the relevant method in the listener object is invoked, and the ComponentEvent is passed to it One or more component events are fired by a Component object just after the component is hidden, made visible, moved, or resized The component hidden and component shown events occur only as the result of calls to a 73 Component 's setvisible method
Steps in Writing a simple Component listener (1/2) Declare a class which implements Component listener Identify the components that you would like to catch the events for. public class ComponentEventDemo... implements ComponentListener pane, label, checkbox, etc. Add the Component Listener to the identified components label.addcomponentlistener(this); 74
Steps in Writing a simple Component listener (2/2) Catch the different events of these components by using four methods of Component Listener public void componenthidden(componentevent e) { } public void componentmoved(componentevent e) {} public void componentresized(componentevent e) {} public void componentshown(componentevent e) {} 75
EventComponentDemo (1/3) 76
EventComponentDemo (2/3) 77
EventComponentDemo (3/3) 78
References David J. Eck, Introduction to Programming Using Java, Version 5.0, December 2006 http://math.hws.edu/javanotes/ Sun, Writing Event Listeners, http://java.sun.com/docs/books/tutorial/uiswing/ events/index.html 79