UID – Event Handling and Listeners Boriana Koleva

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
TCU CoSc Programming with Java Handling Events.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
10.1 AWT The AWT classes Users today expect a Graphical User Interface (GUI) Improves application usability Difficult to implement cross-platform.
Events in Java Swing Chris North cs3724: HCI. Typical command line program Non-interactive Linear execution program: main() { code; }
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Welcome to CIS 083 ! Events CIS 068.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Graphical User Interface Components: Part 1 Chapter 11.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
Creating User Interfaces Event-Driven Programming.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Event Handling and Listeners in SWING The practice of event handling.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Chapter 12 Event-Driven Programming
Advanced User Interfaces
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Making Java GUIs Functional
Presentation transcript:

UID – Event Handling and Listeners Boriana Koleva

Event handling and listeners What is an event?  user actions and context  event sources and listeners Why should my programs be event- driven?  User interaction with the GUI

Some typical component events and listeners Act that results in eventListener User clicks a button, presses return while typing in a text field, or chooses a menu item ActionListener User closes a window WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

Implementing listeners (1) Three key bits of code  1) add interface  2) register  3) handle Components can have multiple listeners A simple JButton ActionListener…

Implementing listeners (2) public class myClass … implements ActionListener { … // where setting up occurs (e.g. constructor) JButton button = new JButton(“I am a button”); button.addActionListener(this); … public void actionPerformed(ActionEvent e) { …// respond to event } // end response method } // end class

Types of event listeners (1) Global component listeners  may be used for any Swing components  Types  ComponentListener (changes in size, position, visibility)  FocusListener (whether ability for keyboard input)  KeyListener (key press events, only with focus)  MouseListener (clicks and movement into/out of component area)  MouseMotionListener (changes in position over component)

Types of event listeners (2) Component-specific listeners  relevant to specific components’ actions  Types  ActionListener  CaretListener  ChangeListener  DocumentListener  ItemListener  ListSelectionListener  WindowListener  etc. See:

Working with event listeners Getting event information Low-level events Semantic events Adapters for event handling Inner classes for event handling

Getting event information EventObject class - use sub classes of this to determine what’s happened. Get the firing object with getSource(); Actual event classes sometimes have specific types  e.g. the ComponentListener uses a sub-class of EventObject : ComponentEvent that has getComponent(); Event classes may define methods that return more information  e.g. ActionEvent has a method for getting modifiers (Shift, Alt, Ctrl)

Low-level and semantic events (1) Low-level events - window-system level  e.g. mouse, key, component, container, focus, window  trigger component-independent Semantic events  everything else! – e.g. action, item, list selection  trigger can differ by component  e.g. button click and textfield ‘return’ action events

Low-level and semantic events (2) Listen for semantic events whenever possible  Gives robust and portable code  eg Button - listen for action event rather than mouse event. Means that button responds to keyboard shortcuts.  Compound components  eg combo box - no real way of guaranteeing low level listeners on all look and feel specific components used to form the compound component.

Adapters for event handling (1) Classes which implement listener interfaces must implement all listener methods  e.g. MouseListener has 5 methods: mouseClicked, mouseReleased, mousePressed, mouseEntered, mouseExited This leads to cluttered code  Say you only want mouseClicked to do something then all others have to be implemented but empty Alternative….

Adapters for event handling (2)... is to extend a MouseAdapter class  inherits empty definitions of all five mouseListener methods. Eg: public class MyClass extends MouseAdapter {... someObject.addMouseListener(this);... public void mouseClicked(MouseEvent e) { //Event handler implementation goes here... }

Inner classes for event handling (1) Don’t want to / cant inherit from an adapter class?  there’s no multiple inheritance in Java  eg can’t extend JPanel AND MouseAdapter  Solution: use an inner class public class MyClass extends JPanel { … anObject.addMouseListener(new myAdapter()); … class myAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { // blah } // end mouseClicked } // end inner class } // end MyClass

Inner classes for event handling (2) Anonymous classes -  used to simplify code  good when only 1 instance will ever be needed public class MyClass extends JPanel {... someObject.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { //Event handler implementation goes here } });... }

Threads and Swing (1) Why use them?  Improved perceived performance  Can remove time consuming task from event thread to keep GUI responsive  Initialisation of program so GUI appears faster Potential problems  Deadlock the application if access any realised swing components from non event threads.

Threads and Swing (2) Remember the rule:  Once a Swing component has been realised, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread. If code does not need to be in event thread then: public void actionPerformed(ActionEvent e) { final SwingWorker worker = new SwingWorker() { public Object construct() { //---code that might take a while to execute is here... return someValue; } }; worker.start(); //required for SwingWorker 3 }

Threads and Swing (3) invokeLater()  requests that event thread runs certain code  can be called from any thread  code goes in run method of Runable object  returns immediately without waiting for event thread to execute code. Runnable updateAComponent = new Runnable() { public void run() {component.doSomething(); } }; SwingUtilities.invokeLater(updateAComponent);

Threads and Swing (4) invokeAndWait()  identical to invokeLater() except doesn’t return till event thread has finished executing the code.  Should use this if possible - less chance of deadlock. void showHelloThereDialog() throws Exception { Runnable showModalDialog = new Runnable() { public void run() { JOptionPane.showMessageDialog(myMainFrame, "Hello There"); } }; SwingUtilities.invokeAndWait(showModalDialog); }

Summary - but not the end... Implementing event listeners Types of event listeners Handling event listeners  getting event information  low-level and semantic events  adapters  inner classes - named and anonymous Threads

What Covered So Far? What is Swing? Containers  Frames  Dialogs  (applets) Components  Loads to choose from Layout Managers  ‘Educated Trial and Error’ Events and User Interaction

A simple Swing program Uses components in containers Lays components out correctly Listens for events An example:  SwingExample.java (revisited)…  Code on Course Website…

A (Slightly) More Complex Swing program Uses components in containers (again) Lays components out correctly (again - but more complex) Listens for events - Multiple listeners Another example:  SwingExample2.java