390 likes | 531 Views
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
E N D
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 eventobject (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
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
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: • 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