Events, Event Handlers, and Threads

Slides:



Advertisements
Similar presentations
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
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.
Event-Driven Programming
Intermediate Java1 An example that uses inner classes Week Four Continued.
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.
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Welcome to CIS 083 ! Events CIS 068.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
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.
(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.
– 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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Concurrent Programming and Threads Threads Blocking a User Interface.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
UID – Event Handling and Listeners Boriana Koleva
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
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.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
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.
Event Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
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.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUI Programming using Java - Event Handling
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
CHAPTER Reacting to the user.
A First Look at GUI Applications
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation
CSE 331 Software Design and Implementation
Ellen Walker Hiram College
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Event Driven Programming
Introduction to Computing Using Java
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
Chapter 16 Event-Driven Programming
CSE 331 Software Design & Implementation
Presentation transcript:

Events, Event Handlers, and Threads CSC 143 Java Events, Event Handlers, and Threads

Overview Topics Event-driven programming Events in Java Event Listeners Event Adapters Threads Inner Classes

Classic Data Processing Input specified as part of the program design Example: process bank account deposits Repeated set of transactions Each transaction consists of a deposit slip (transaction header) followed by 1 or more checks to be deposited to the account Program expects input in required order Program structure mirrors input organization while (more input) { //read and process transaction header //read and process individual checks }

Event-Driven Programming Idea: program initializes itself then accepts events in whatever random order they occur Kinds of events Mouse move/drag/click, Keyboard, Touch screen, Joystick, game controller Window resized or components changed Activity over network or file stream Timer interrupt (can still think of this as processing an “input stream”, but point of view is basically different) First demonstrated in the 1960s(!); major developments at Xerox PARC in the 1970s (Alto workstation, Smalltalk) Available outside research community with Apple Macintosh (1984)

Java Events An event is represented by an event object AWT/Swing events are subclasses of AWTEvent. Some examples: ActionEvent – button pressed KeyEvent – keyboard input MouseEvent – mouse move/drag/click/button press or release All user interface components generate events when appropriate Event objects contain information about the event User interface object that triggered the event Other information appropriate for the event. Examples: ActionEvent – contents of button text generating event (if from a button) MouseEvent – mouse coordinates of the event All in java.util.event – need to import this to handle events

Event Listeners Basic idea: any object that is interested in an event registers itself with the component that can generate the event The object must implement the appropriate Interface ActionListener, KeyListener, MouseListener (buttons), MouseMotionListener (move/drag), others … When the event occurs, the appropriate method of the object is called actionPerformed, keyPressed, keyReleased, keyTyped, mouseClicked, MouseDragged, etc. etc. etc. Reminder – because these are part of an Interface, you can't change their signatures. An event object describing the event is a parameter to the receiving method

Example: Mouse Clicks public class Mouser extends JPanel implements MouseListener { /** Constructor – register this object to listen for mouse events */ Mouser( ) { super( ); addMouseListener(this); } /** Process mouse click */ public void mouseClicked(MouseEvent e) { System.out.println(“mouse click at x = ” + e.getX( ) + “ y = “ e.getY( )); Also must implement the other events in MouseListener (if not Mouser is abstract)

Example: Draw Button Idea: add a button to the graphical view of the polygon application to redraw a polygon First, in the MainClass, add a JButton

Button/View Layout In the buildGUI method // place a button at the bottom of the frame JButton draw = new JButton("Draw polygon"); JPanel southPanel = new JPanel(); southPanel.add(draw); southPanel.setBackground(Color.WHITE); frame.add(southPanel, BorderLayout.SOUTH);

Handling Button Clicks Who should handle the draw button clicks? Not the PolygonModel object – shouldn’t know about views But need to catch the event and then call methods in the PolygonModel to carry out the pause/resume One solution: create a listener object New class: PolygonController Code in MainClass PolygonController controller= new PolygonController(model); draw.addActionListener(controller);

Listener Object public class PolygonController implements ActionListener { // instance variables PolygonModel model; // the model we are controlling /** Constructor for objects of class PolygonController */ public PolygonController(PolygonModel model) { this.model = model; } /** Process button clicks by creating a new polygon*/ public void actionPerformed(ActionEvent e) { ???

Event Adapter Classes Interfaces like MouseListener and WindowListener contain many methods; often we only are interested in one or two Alternative to implementing the interface and having to provide empty implementations for uninteresting methods – adapter classes Java.awt.event includes an abstract class with empty implementations of all required methods for each of the event listener interfaces KeyAdapter (for KeyListener), MouseAdapter (for MouseListener), WindowAdapter (for WindowListener), etc. Extend and override only what you need to create a listener object

Threads and The AWT Event Thread Java supports "threads": apparently concurrently executing streams of instructions. User programs have at least one thread running Not hard to create additional threads Can be tricky to coordinate multiple threads The Java system has several threads running all the time One important system thread: the AWT event dispatcher All AWT/Swing event handlers execute in this thread Consequence: your event handlers may be running simultaneously with your application code

Another approach: anonymous class What we did public class PolygonController implements ActionListener{ public void actionPerformed(ActionEvent e) { if (model != null) { model.createPolygon(width, height); } Controller needs to know about the model, etc. Can be done within the MainClass where all of the information is available

Towards a Solution: Inner Classes Java 1.1 and later allows classes to be nested Inner classes define a new scope nested in the containing class Inner classes can access instances variables and methods of the containing class Inner classes can be public, protected, or private Example: Point2D has two inner classes, named Float and Double Are public, so can be used outside of class Point2D, as Point2D.Float and Point2D.Double Inner classes in event handling A class like class PolygonController implements ActionListener{...} can be a private inner class: is only needed once, and only inside the containing class

Solution: Anonymous Inner Classes For the action listener, all we need to do is create one instance of the inner class and add it as a mouse listener Doesn’t really need a name(!) Solution: create one instance of an anonymous inner class Warning!!! Ghastly syntax ahead. Here’s how to create a new object of an anonymous inner class new <classname> ( <constructor parameters> ) { <method overrides> }

Anonymous class for the controller public static void buildGUI( ) { // build GUI code (JFrame, etc.) // Create inner class instance to listen for mouse clicks draw.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.createRandomPolygon(centerPanel.getWidth(), centerPanel.getHeight()); } }); // no need to have a top level class for the controller } //end method buildGUI

Summary Event-driven programming Event objects Event listeners – anything that implements the relevant interface Must register with object generating events as a listener Listener objects – handle events by passing them along to other objects Event adapter classes – implementations of event interfaces with empty methods Extend and override only what you want Commonly used to create instances of anonymous inner classes that listen for events