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,

Download Report

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,

Lecture 5

Event Handling

1

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 2

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 3

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 4

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 add

Type

Listener(

Type

Listener

el

) i.e. addKeyListener(), addMouseMotionListener() When an event occurs, all registered listeners are notified and receive a copy of the event object (called multicasting) 5

Event sources (contd.)

  Some sources allow only one listener to register (unicasting): publc void add

Type

Listener(

Type

Listener

el

) throws java.util.TooManyListenersException

A source also allows a listener to unregister publc void remove

Type

Listener(

Type

Listener

el

) i.e. removeKeyListener() 6

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 7

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 8

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 ComponentEvent When a scroll bar is manipulated ContainerEvent A component is hidden, moved, resized or become visible A component is added to or removed from a container A component gains or loss keyboard focus FocusEvent InputEvent KeyEvent MouseEvent Superclass of all input event classes Input is received from the keyboard Mouse is dragged, moved, clicked, released 9

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

11

Button

Sources of events

Generates action event when it is pressed

Checkbox

Generates item events when the check box is selected or deselected

Choice List

Generates item events when the choice is changed

1

. Action events when an item is double-clicked

2

. Item events when an item is selected/deselected

Menu Item Scrollbar Text box Window 1

.Action events when a menu item is selected

2

.Item events when checkable menu item selected Adjustment events when scroll bar is manipulated Text events when user enters a character Window events when window is activated, closed, deactivated, opened etc 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

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

Commonly used Event Listener Interfaces (contd.)

MouseListener Five methods, mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased MouseMotion Listener TestListener Two methods, mouse is dragged or moved One method, textChanged WindowEvent Seven events, windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowicinified, windowOpened 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

19

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

20

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

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

The class hierarchy

Component Container MenuContainer Interface Window Frame Panel 23

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 24

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

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

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 27

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 28

     

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 29

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 30

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 31

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 32

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 33

Working with Graphics (contd.)

  Graphics class defines a number of drawing functions:  drawLine(int

start

X,int

start

Y,int

end

X,int

end

Y)     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 34

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 35

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 36

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 37

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 38

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 39