Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 5 Event Handling.

Similar presentations


Presentation on theme: "Lecture 5 Event Handling."— Presentation transcript:

1 Lecture 5 Event Handling

2 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

3 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

4 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

5 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)

6 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()

7 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

8 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

9 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

10 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

11

12 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

13 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

14 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

15 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

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

17 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

18 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

19

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

21 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)

22 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)

23 The class hierarchy Component Container MenuContainer Window Panel
Interface Frame

24 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

25 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)

26 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()

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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


Download ppt "Lecture 5 Event Handling."

Similar presentations


Ads by Google