chapter 27 javabeans and bean events

24
1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pears on Education, Inc. All rights reserved. 0-13-148952-6 Chapter 27 JavaBeans and Bean Events Chapter 27 JavaBeans and Bean Events Chapter16 A ppletsand M ultim edia Chapter 28 Containers, Layout Managers, and Borders Chapter 29 Menus, Toolbars, Dialogs, and Internal Frames Chapter 30 MVC and Swing Models Chapter 31 JTable and JTree

Upload: caesar-mcclure

Post on 30-Dec-2015

39 views

Category:

Documents


3 download

DESCRIPTION

Chapter 27 JavaBeans and Bean Events. Objectives. To know what a JavaBeans component is (§27.2). To discover the similarities and differences between beans and regular objects (§27.2). To understand JavaBeans properties and naming patterns (§27.3). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 27  JavaBeans and Bean Events

1Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Chapter 27 JavaBeans and Bean Events

Chapter 27 JavaBeans and Bean Events

Chapter 16 Applets and Multimedia

Chapter 28 Containers, Layout Managers, and Borders

Chapter 29 Menus, Toolbars, Dialogs, and Internal Frames

Chapter 30 MVC and Swing Models

Chapter 31 JTable and JTree

Page 2: Chapter 27  JavaBeans and Bean Events

2Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

ObjectivesTo know what a JavaBeans component is

(§27.2).To discover the similarities and differences

between beans and regular objects (§27.2).To understand JavaBeans properties and naming

patterns (§27.3).To review the Java event delegation model

(§27.4).To create custom event classes and listener

interfaces (§27.5 optional).To develop source components using event sets

from the Java API or custom event sets (§27.6).

Page 3: Chapter 27  JavaBeans and Bean Events

3Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

What is JavaBean?A JavaBeans component is a serializable public class with a public no-arg constructor.

Every GUI class is a JavaBeans component, because (1) it is a public class; (2) it has a public no-arg constructor; (3) It is an extension of java.awt.Component, which implements java.io.Serializable.

Data members Methods Constructors

public class public no-arg constructor serializable may have accessor/mutator methods may have registration/deregistration methods

class

JavaBeans Component Minimum requirement

Optional requirement

Page 4: Chapter 27  JavaBeans and Bean Events

4Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Why JavaBeans?The JavaBeans technology was developed to enable the programmers to rapidly build applications by assembling objects and test them during design time, thus making reuse of the software more productive.

JavaBeans is a software component architecture that extends the power of the Java language by enabling well-formed objects to be manipulated visually at design time in a pure Java builder tool, such as JBuilder and NetBeans.

Page 5: Chapter 27  JavaBeans and Bean Events

5Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

JavaBeans Properties and Naming Patterns

The get method is named get<PropertyName>(),

which takes no parameters and returns an object of the type identical to the property type.

For a property of boolean type, the get method should be named is<PropertyName>(),

which returns a boolean value. The set method should be named

set<PropertyName>(newValue),

which takes a single parameter identical to the property type and returns void.

Page 6: Chapter 27  JavaBeans and Bean Events

6Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Properties and Data FieldsProperties describe the state of the bean. Naturally, data fields are used to store properties. However, a bean property is not necessarily a data field. For example, in the MessagePanel class in Example 12.5 in Chapter 13, you may create a new property named messageLength that represents the number of the characters in message. The get method for the property may be defined as follows: 

public int getMessageLength() { return message.length();}

 NOTE: A property may be read-only with a get method but no set method, or write-only with a set method but no get method.

Page 7: Chapter 27  JavaBeans and Bean Events

7Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Bean EventsA bean may communicate with other beans. The Java event delegation model provides the foundation for beans to send, receive, and handle events. When something happens to a bean, such as a mouse click on a javax.swing.JButton bean, an event object is created to encapsulate information pertaining to the event. The bean passes the event object to the interested beans for the event to be processed.

Events are typically generated by Java GUI components, such as javax.swing.JButton, but are not limited to GUI components. This section introduces the development of custom events and the beans that can generate events.

Page 8: Chapter 27  JavaBeans and Bean Events

8Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

The Event Delegation Model

source: SourceClass

+addXListener(XListener listener)

listener: ListenerClass User Action

Trigger an event

XListener +handler(XEvent event)

Internal function of the source object

event: XEvent listener1 listener2 … listenern

+handler(XEvent

Register by invoking source.addXListener(listener);

Keep it a list

Invoke listener1.handler(event) listener2.handler(event) … listenern.handler(event)

Figure 14.2

Page 9: Chapter 27  JavaBeans and Bean Events

9Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Predefined Event Pairs(Event Classes and Listener Interface)

Examples:

ActionEvent/ActionListener

AdjustmentEvent/AdjustmentListener

AWTEvent EventObject

AdjustmentEvent

ComponentEvent

TextEvent

ItemEvent

ActionEvent

InputEvent

WindowEvent

MouseEvent

KeyEvent

ContainerEvent

FocusEvent

PaintEvent

ChangeEvent HyperLinkEvent InternalFrameEvent ListSelectionEvent

TableModelEvent

TableColumnEvent TreeModelEvent TreeSelectionEvent

TreeExpansionEvent javax.swing.event package

Page 10: Chapter 27  JavaBeans and Bean Events

10Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Examples of Event Pairs

java.awt.event.ActionEvent

actionCommand: String

modifier: int

when: long

+ActionEvent(source: Object, id: int, command: String)

+getActionCommand(): String

+getModifier(): int

+getWhen(): long

java.util.EventListener

java.util.EventObject

+EventObject(source: Object)

+getSource(): Object

java.awt.AWTEvent

java.awt.event.ActionListener

+actionPerformed(ActionEvent e): void

Page 11: Chapter 27  JavaBeans and Bean Events

11Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Source Components

Fire and process event by invoking the event handler from each listener in the vector

Source Component

Register listener method Deregister listener method

A vector (stores the listener objects)

Detect events

The source component detects events and processes the events by invoking the event listeners' handler.

Page 12: Chapter 27  JavaBeans and Bean Events

12Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Listener Components

The listener is registered with the source, and the source invokes the listener's handler to process the event.

Process event

actionPerformed(ActionEvent e)

Source Component Listener Component

addActionListener(ActionListener l) removeActionListener(ActionListener l)

JButton jbt = new JButton(); // Create a source object MyListener listener = new MyListener (); // Create a listener object jbt.addActionListener(listener); // Register listener to the source

Test Class

Listener vector MyListener class implements ActionListener

JButton

Invoke listener’s actionPerformed method Generate an

event

Page 13: Chapter 27  JavaBeans and Bean Events

13Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Creating Custom Event PairsYou have already used event sets (e.g., ActionEvent/ActionListener) and

event source components (JButton) in Java GUI programming. You can

create your own event sets and source components.

A custom event class must extend java.util.EventObject or a subclass of

java.util.EventObject. Additionally, it may provide constructors to create

events, data members and methods to describe the event.

A custom event listener interface must extend java.util.EventListener or a

subinterface of java.util.EventListener, and define the signature of the

handlers for the event. By convention, the listener interface should be

named <Event>Listener for the corresponding event class named

<Event>.

Page 14: Chapter 27  JavaBeans and Bean Events

14Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Example: Creating a Custom Event Set

Problem: This example creates a custom event named TickEvent for

describing tick events, and its corresponding listener interface TickListener

for defining a tick handler.

TickEvent

-tickCount: long

-tickInterval: long

+TickEvent(source: Object)

+getTickCount(): long

+getTickInterval(): long

+setTickCount(tickCount: long): void

+setTickInterval(tickInterval: long): void

java.util.EventListener

java.util.EventObject

TickListener

+handleTick(TickEvent e): void

TickEventTickEvent

TickListenerTickListener

Page 15: Chapter 27  JavaBeans and Bean Events

15Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Creating Custom Source Components

Unicast Registration Methods:

A source component must have the appropriate registration and

deregistration methods for adding and removing listeners.

Events can be unicasted (only one object is notified of the

event) or multicasted (each object in a list of listeners is

notified of the event). The naming pattern for adding a

unicast listener is

public void add<Event>Listener(<Event>Listener l)

throws TooManyListenersException;

Page 16: Chapter 27  JavaBeans and Bean Events

16Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Creating Custom Source Components

Multicast Registration Methods:

The naming pattern for adding a multicast listener is the same, except that it

does not throw the TooManyListenersException.

public void add<Event>Listener(<Event>Listener l)

The naming pattern for removing a listener (either unicast or multicast) is:

public void remove<Event>Listener(<Event>Listener l)

A source component contains the code that creates an event object and

passes it to the listening components by calling a method in the listener's

event listener interface. You may use a standard Java event class like

ActionEvent to create event objects or may define your own event

classes if necessary.

Page 17: Chapter 27  JavaBeans and Bean Events

17Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Example: Creating a Source Component

Problem: This example creates a custom source component that generates a tick event at every specified time interval in milliseconds. Create a custom source component that is capable of generating a tick event at a variant time interval. The component contains the properties tickCount, tickInterval, maxInterval, minInterval, and step. The component adjusts the tickInterval by adding step to it after a tick event occurs. If step is 0, tickInterval is unchanged. If step > 0, tickInterval is increased. If step < 0, tickInterval is decreased. If tickInterval > maxInterval or tickInterval < minInterval, the component will no longer generate tick events.

NOTE: You learned to use javax.swing.Timer to control the animation in Chapter 19, “Multithreading.” The Timer class generates a timer at a fixed time interval. This new component can generate a tick event at a variant time interval as well as a fixed time interval.

Page 18: Chapter 27  JavaBeans and Bean Events

18Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Example: Creating a Source Component

TickTick

Tick

-tickCount: long

-tickInterval: long

-maxInterval: long

-minInterval: long

-step: long

-e: TickEvent

-tickListenerList: ArrayList

-suspended: boolean

-timer: javax.swing.Timer

+Tick()

+Tick(tickInterval: int, maxInterval: int, minInterval: int, step: int)

+resume(): void

+suspend(): void

+addTickListener(l: TickListener): void

+removeTickListener(l: TickListener): void

-processEvent(e: TickEvent): void

java.io.Serializable

JavaBeans property for tickCount (default 0).

JavaBeans property for tickInterval (default 100).

JavaBeans property for maxInterval (default 5000).

JavaBeans property for minInterval (default 1).

JavaBeans property for step (default 0).

Tick event created from the Tick object.

Stores the TickEvent listeners.

Indicates whether tick is suspended.

Timer for controlling the tick.

Creates a Tick object with default properties.

Creates a Tick object with the specified properties.

Resumes the tick.

Suspends the tick.

Adds a new listener to this object.

Removes a listener from this object.

Processes the event.

Page 19: Chapter 27  JavaBeans and Bean Events

19Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Example: Using the TickEvent Class

Problem: Write a program that displays a moving message.

Solution: You can write the code using the Thread.sleep(millis) method or the Timer class to control the animation (See Exercise 19.11). This example uses the Tick class to display the message periodically.

DisplayMovingMessageDisplayMovingMessage RunRun

JApplet

DisplayMovingMessage -tick: Tick -messagePanel: MovingMessage +DisplayingMessage()

Tick

TickEvent

MovingMessage

+handleTick(TickEvent e)

TickListener

Page 20: Chapter 27  JavaBeans and Bean Events

20Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Interaction Between Source and Listener Components

The listener messagePanel is registered with the source tick, and the source invokes the listener's handler handleTick to process the event.

Process event

handleTick(TickEvent e)

Source Component Listener Component

addTickListener(TickListener l) removeTickListener(TickListener l)

Tick tick = new Tick(); // Create a source object MovingMessage messagePanel = new MovingMessage(); // Create a listener object tick.addTickListener(messagePanel); // Register listener to the source

DisplayMovingMessage

Listener vector MovingMessage class implements TickListener

Tick

Invoke listener’s handleTick method Generate an

event

Page 21: Chapter 27  JavaBeans and Bean Events

21Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Working with Existing Event Sets

TickEvent and TickListener is a new event pair. Most of the time you don't need to create your own event pairs unless you want to encapsulate information not available in the existing event classes, as in the case of the TickEvent class that contains tick count and tick interval. If you don't need the tick count and tick interval contained in a tick event. There is no need to create a TickEvent class; instead you can use java.awt.ActionEvent and let the Tick class generate an ActionEvent instance when a tick event occurs.

Page 22: Chapter 27  JavaBeans and Bean Events

22Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Example: Developing a Source Component Using Existing Event Sets

Problem: This example presents a new component that generates an ActionEvent when a tick event occurs rather than using a TickEvent. Use this new component to rewrite the preceding example to display a moving message.

TickUsingActionEventTickUsingActionEvent

RunRun

JApplet

DisplayingMessageUsingActionEvent -tickUsingActionEvent1: TickUsingActionEvent -messagePanel: MovingMessageNew +DisplayingMessageUsingActionEvent()

TickUsingActionEvent

ActionEvent

MovingMessageNew

+actionPerformed(ActionEvent e)

ActionListener

DisplayingMessageUsingActionEventDisplayingMessageUsingActionEvent

Page 23: Chapter 27  JavaBeans and Bean Events

23Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Interaction Between Source and Listener Components

The listener messagePanel is registered with the source tick, and the source invokes the listener's handler actionPerformed to process the event.

Process event

actionPerformed(ActionEvent e)

Source Component Listener Component

addActionListener(ActionListener l) removeActionListener(ActionListener l)

TickUsingActionEvent tick = new TickUsingActionEvent (); // Create a source object MovingMessageNew messagePanel = new MovingMessageNew(); // Create a listener object tick.addActionListener(messagePanel); // Register listener to the source

DisplayingMessageUsingActionEvent

Listener vector MovingMessageNew class implements ActionListener

TickUsingActionEvent

Invoke listener’s actionPerformed method Generate an

event

Page 24: Chapter 27  JavaBeans and Bean Events

24Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Note to the InstructorYou may cover Chapter 30 now.