1 / 39

Lecture 5

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

tovah
Download Presentation

Lecture 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 eventobject (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

  10. Main event classes in java.awt.event (contd.)

  11. Sources of events

  12. 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

  13. Commonly used Event Listener Interfaces

  14. Commonly used Event Listener Interfaces (contd.)

  15. Examples • Chapter 20, listing 1, MouseEvents • Chapter 20, listing 2, SimpleKey

  16. 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

  17. 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

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

  19. 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)

  20. 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)

  21. The class hierarchy Component Container MenuContainer Window Panel Interface Frame

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

  23. 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)

  24. 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()

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

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. Drawing functions: • 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

  34. 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

  35. 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

  36. 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

  37. 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

More Related