Lecture 5 Event Handling.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Event Handling.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
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.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Topics AWT Classes Window Fundamentals Working with Frame Windows Creating a Frame Window in an Applet Creating a Windowed Program Displaying Information.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
10.1 AWT The AWT classes Users today expect a Graphical User Interface (GUI) Improves application usability Difficult to implement cross-platform.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Io package as Java’s basic I/O system continue’d.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Abstract Window Toolkit (AWT) The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include:  A rich set.
Graphical User Interface Components: Part 1 Chapter 11.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
– 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.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Computer Science [3] Java Programming II - Laboratory Course Lab 4: Common GUI Event Types and Listener Interfaces Layout Mangers Faculty of Engineering.
© 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
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.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
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.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
AWT Package. Java GUI classes are contained in the java.awt package. Java GUI classes are contained in the java.awt package. A graphical Java program.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Events (Chapter 11) Java Certification Study Group January 25, 1999 Mark Roth.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
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.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
1 Lecture 8: User Interface Components with Swing.
CS 240 Week 9. EventQueue.invokeLater In Swing, all user interface operations must occur on the “UI thread” – All components should be created on the.
AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java. Java AWT components are platform-dependent i.e.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
CSC 205 Programming II Lecture 5 AWT - I.
Welcome To java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Aum Amriteshwaryai Namah
A First Look at GUI Applications
Advanced User Interfaces
Abstract Window ToolKit (AWT)
Programming in Java Event Handling
GUI Programming III: Events
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
AWT Components and Containers
Presentation transcript:

Lecture 5 Event Handling

Introduction Event handling is at the core of successful applet and AWT programming Most commonly events are generated by mouse, keyboard, and various controls, such as a push button Events are supported by java.awt.event package The way in which events are handled changed significantly in the newer versionof Java

The Delegation Event Model Source generates an event and sents it to one or more listeners Listeners simply waits until it receives an event. Once received, they process the event and returns Event processing code is cleanly separated from user interface code Listeners must register with a source in order to receive an event notification. So, notifications are sent only to listeners that want to receive them

Events Event is an object that describes a state change in a source Activities that cause to generate events are pressing a button, entering a character via keyboard, selecting an item in a list, clicking the mouse Events can be generated without user interaction, i.e. timer expired, counter exceeded a value, s/w or h/w failure

Event sources A source is an object that generates an event (due to change of internal state) A source may generate more than one type of event A source must register listeners in order to notify them about a specific type of event publc void addTypeListener(TypeListener el) i.e. addKeyListener(), addMouseMotionListener() When an event occurs, all registered listeners are notified and receive a copy of the event object (called multicasting)

Event sources (contd.) Some sources allow only one listener to register (unicasting): publc void addTypeListener(TypeListener el) throws java.util.TooManyListenersException A source also allows a listener to unregister publc void removeTypeListener(TypeListener el) i.e. removeKeyListener()

Event Listeners A listener is an object that is notified when an event occurs Responsibility of a listener: Register with one or more sources Implement methods to receive and process these notifications i.e. MouseMotionListener interface defines two methods to receive notifications when mouse is dragged or moved

Event classes EventObject (in java.util package) is the superclass for all events EventObject (Object src) Its getSource() method returns the source of the event and toString() method returns the string equivalent of the event AWTEvent (in java.awt package) is a subclass of EventObject and superclass of all AWT-based events Its getID() method can be used to determine the type of the event

Main event classes in java.awt.event ActionEvent Generated when a button is pressed, list item is double-clicked, or a menu item is selected Adjustment Event When a scroll bar is manipulated ComponentEvent A component is hidden, moved, resized or become visible ContainerEvent A component is added to or removed from a container FocusEvent A component gains or loss keyboard focus InputEvent Superclass of all input event classes KeyEvent Input is received from the keyboard MouseEvent Mouse is dragged, moved, clicked, released

Main event classes in java.awt.event (contd.) ItemEvent A check box, list item is clicked or choice selection is made TextEvent The value of a text area or text field is changed WindowEvent Window is actiated, closed, deactivated, opened or quit

Sources of events Button Checkbox Choice List Menu Item Scrollbar Generates action event when it is pressed Checkbox Generates item events when the check box is selected or deselected Choice Generates item events when the choice is changed List 1. Action events when an item is double-clicked 2. Item events when an item is selected/deselected Menu Item 1.Action events when a menu item is selected 2.Item events when checkable menu item selected Scrollbar Adjustment events when scroll bar is manipulated Text box Text events when user enters a character Window Window events when window is activated, closed, deactivated, opened etc

Event Listener Interfaces Listeners are created by implementing one or more of the interfaces defined by java.awt.event package When a event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument

Commonly used Event Listener Interfaces ActionListener Defines one method to receive action events AdjustmentListener One method to receive adjustment events ComponentListener Four methods to recognize when a component is hidden, moved, resized or shown ContainerListener Two methods, added and removed FocusListener Two methods, focusGained, focusLost ItemListener One method, itemStateChanged KeyListener Three methods, KeyPressed, KeyReleased, KeyTyped

Commonly used Event Listener Interfaces (contd.) MouseListener Five methods, mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased MouseMotion Listener Two methods, mouse is dragged or moved TestListener One method, textChanged WindowEvent Seven events, windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowicinified, windowOpened

Examples Chapter 20, listing 1, MouseEvents Chapter 20, listing 2, SimpleKey

Adapter classes Adapter classes simplify the creation of event handlers in certain situations It allows to receive and process only some of the events that are handled by a particular event listener interface We can define a new class to act as an event listener by extending one of the adapter classes and implementing only necessary events. Other unimplemented methods are handled automatically by adapter interfaces

Adapter classes example MouseMotionAdapter class has two methods, like MouseMotionListener: mouseDragged() mouseMoved() We can extend MouseMotionAdapter and implement only mouseDragged() in my own way. Empty implementation of mouseMoved() would handle the mouse events for us

Introducing the AWT: Working with Windows, Graphics, and Text

Introduction The Active Window Toolkit (AWT) contains numerous classes and methods that allow us to create and manage windows AWT can be used to create both applet windows and stand-alone windows for GUI environment AWT classes are contained in the java.awt package Some AWT classes: Table 21-1 (i.e. Button, BorderLayout, Canvas, Checkbox, Choice, Color, Component, Container, FlowLayout, Frame, Font, Image, Label, List, Menu, Panel, Scrollbar)

Window Fundamentals The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level Two most common windows are derived from Panel (used by Applet) Frame (creates standard windows)

The class hierarchy Component Container MenuContainer Window Panel Interface Frame

Component An abstract class that encapsulates all of the attributes of a visual component All user interface elements are subclasses of Components Provides methods for managing events (i.e. mouse and keyboard input), positioning and resizing the window and repainting Remember current foreground and background color and current text font

Container Allow other component objects to be nested within it Other Container objects can be stored inside of a Container and thus provide multilevel containment system Also responsible for laying out components that it contains (by the use of layout manager)

Panel A concrete subclass of Container and superclass for Applet When screen output is directed to an applet, it is drawn on the surface of a Panel object It does not contain title bar, menu bar or border (applet viewer provides title and border from itself) Components can be added to a Panel by add() method (inherited from Container) Components can be positioned and resized by setLocation(), setSize() and setBounds()

Window Window class creates a top-level window A top-level window is not contained within any other object It sits directly on the desktop Generally we don’t create Window objects directly, rather we create subclass of Window called Frame

Frame It has title bar, menu bar, borders, and resizing corners Frame object can be created within an applet, but that is not well practiced, as applet application can do some malicious things in the background When a frame window is created by a program rather than an applet, a normal window is created

Working with Frame windows Frame can be used as a child window within applet, a top-level window or child windows for applications Frame() // standard window that does not contain title Frame(String title) The size of the window can be mentioned during construction, rather it is set afterwards setSize(int newWidth, int newHeight) setSize(dimension newSize) getSize() method is used to obtain the current size setVisible(boolean visibleFlag) is used to show or hide a window, specially when a window is closed setTitle(String newTitle) is used to set the new title To intercept a window-close event, we have to implement the windowClosing() method of WindowListener interface

Creating a frame window in an Applet Generally we don’t create Frame objects directly but create a subclass of Frame and override Frame’s methods and handle events Creating an object of subclass of a frame does not make initially visible. We make visible by setVisible() method When created, the window is given a default height and width and can be changed at anytime Example: AppletFrame

Handling Events in a Frame Window We can use and manage a frame window that we create just like we manage our applet’s main window (as both are subclass of Component) Whenever an event occurs in a window, the event handlers defined by that window will be called Each window handles its own events For applet window, we don’t need to register window listener, as window closing event is automatically handled by applet Example: WindowEvents

Creating a Windowed Program We can create a stand-alone AWT based applications To do so, we need to create an instance of the window or windows inside main() After creating, we need to set its visibility equals to true Example: AppWindow

Working with Graphics All graphics are drawn relative to a window The origin of each window is the top-left corner and is 0,0. Coordinates are specified in pixels All output to a window takes place through a graphics context, defined in Graphics class Objects are drawn and filled in the currently selected graphics color, which is black by default

Working with Graphics (contd.) Graphics class defines a number of drawing functions: drawLine(int startX,int startY,int endX,int endY) drawRect(int top,int left,int width, int height) fillRect(int top,int left,int width, int height) drawRoundRect(int top,int left,int width, int height,int xDiam,int yDiam) fillRoundRect(int top,int left,int width, int height,int xDiam,int yDiam) Example: Lines and Rectangles

Drawing functions: Example: Ellipses, Arcs and HourGlass drawOval(int top,int left,int width, int height) fillOval(int top,int left,int width, int height) drawArc(int top,int left,int width, int height,int startAngle, int sweepAngle) fillArc(int top,int left,int width, int height,int startAngle, int sweepAngle) drawPolygon(int x[], int y[], int numPoints) fillPolygon(int x[], int y[], int numPoints) Example: Ellipses, Arcs and HourGlass

Sizing Graphics If we want to size a graphics object to fit the current size of the window, we have to obtain the current dimensions of the window Dimension getSize() Then we can scale our graphical output accordingly Example: Resize

Working with color We can create our own color by: Color(int red,int green,int blue) //values are 0 to 255 Color(int rgbValue) // values are like 0xffc00034 Color(float red, int green, float blue) //values are 0 to1.0 setForeground() and setBackground() is used to set any color as foreground or background setColor() is used to set current graphics color getColor() is used to know current color Example: ColorDemo

Working with Fonts AWT supports multiple type font-manipulation operations and dynamic selection Each font has a family name (the general name like Courier), a logical name (the category like Monospaced) and face name (specific font like Courier Italic) String[] getAvailableFontFamilyNames() is used to get available fonts Font[] getAllFonts() return an array of Font objects for all available fonts

Working with Fonts (contd.) To select a new font, first construct a Font object by: Font (string fontName,int fontStyle,int pointSize) Then set the font by setFont(Font fontObj) Font style may be Font.PLAIN, Font.BOLD etc. Example: ShowFonts and SampleFonts