GUI Event Handlers (Part I)

Similar documents
GUI Event Handlers (Part II)

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Handling Mouse and Keyboard Events

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

The AWT Event Model 9

Java Event Handling -- 1

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Event Driven Programming

Advanced Java Programming (17625) Event Handling. 20 Marks

CS 251 Intermediate Programming GUIs: Event Listeners

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

COMPSCI 230. Software Design and Construction. Swing

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Graphical User Interface (GUI)

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Advanced Computer Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

Programming in the Large II: Objects and Classes (Part 2)

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Class 16: The Swing Event Model

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Graphical User Interface (GUI)

GUI in Java TalentHome Solutions

Programming in the Small II: Control

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

GUI Components: Part 1

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Advanced Computer Programming

CSE 331 Software Design & Implementation

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

Dr. Hikmat A. M. AbdelJaber

SD Module-1 Advanced JAVA

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

SD Module-1 Advanced JAVA. Assignment No. 4

Packages: Putting Classes Together

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CS11 Java. Fall Lecture 4

Lecture 19 GUI Events

CS11 Java. Fall Lecture 3

Graphical User Interfaces. Comp 152

2. (True/False) All methods in an interface must be declared public.

GUI Software Architecture

Which of the following syntax used to attach an input stream to console?

Graphical User Interfaces 2

GUI Programming: Swing and Event Handling

Lecture 9. Lecture

MIT AITI Swing Event Model Lecture 17

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Unit 7: Event driven programming

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

Jonathan Aldrich Charlie Garrod

CS111: PROGRAMMING LANGUAGE II

Window Interfaces Using Swing Objects

Chapter 6: Graphical User Interfaces

Window Interfaces Using Swing Objects

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Widget. Widget is a generic name for parts of an interface that have their own behaviour. e.g., buttons, progress bars, sliders, drop-down

Chapter 12 Advanced GUIs and Graphics

Introduction to the JAVA UI classes Advanced HCI IAT351

7. Program Frameworks

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CS 112 Programming 2. Lecture 14. Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations

8. Polymorphism and Inheritance

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Java: Graphical User Interfaces (GUI)

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

BM214E Object Oriented Programming Lecture 13

PIC 20A GUI with swing

Swing from A to Z Some Simple Components. Preface

AP CS Unit 11: Graphics and Events

This page intentionally left blank

Lecture 3: Java Graphics & Events

CS211 GUI Dynamics. Announcements. Motivation/Overview. Example Revisted

CS 11 java track: lecture 3

Programming Languages and Techniques (CIS120)

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Widget Toolkits CS MVC

Event Handling in JavaFX

(Incomplete) History of GUIs

EVENTS, EVENT SOURCES AND LISTENERS

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Interacción con GUIs

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Transcription:

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