62
Chapter 8: JavaBeans Java Programming - Advanced Topics

Chapter 8: JavaBeans

  • Upload
    ishana

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 8: JavaBeans. Java Programming - Advanced Topics. Objectives. In this unit you will: Learn what the JavaBeans component model is Create your own JavaBean components Learn how beanboxes consume beans - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 8: JavaBeans

Chapter 8: JavaBeans

Java Programming - Advanced

Topics

Page 2: Chapter 8: JavaBeans

Objectives

In this unit you will:

• Learn what the JavaBeans component model is

• Create your own JavaBean components

• Learn how beanboxes consume beans

• Learn the characteristics of a JavaBean, including how to define the properties, methods, and events for your own beans

• Add custom event types to your beans

Page 3: Chapter 8: JavaBeans

Objectives

In this unit you will:• Use JavaBeans information classes to make all

features available to beanboxes that operate on your beans

• Provide customized editors so that properties of your beans can be edited in a beanbox

• Use the BeanContext API to create JavaBeans that can search their environment for available services

• Gain a basic understanding of what an Enterprise JavaBean is

Page 4: Chapter 8: JavaBeans

JavaBeans Component Model

• Increasingly, Integrated Development Environment (IDEs) for the Java platform, such as IBM’s VisualAge for Java, are being designed to accept JavaBean components

• When you use a visual development environment, the distinguishing feature of components such as JavaBeans becomes clear

Page 5: Chapter 8: JavaBeans

JavaBeans Component Model

• The components are manipulated at design time as binary executables

• JavaBeans is the first component model for the Java platform

• It is possible to define classes that conform to the specification of the JavaBeans component model and are also compatible with other Java programming models

Page 6: Chapter 8: JavaBeans

What Makes a Class a Bean

• The core classes and interfaces in the packages java.beans and java.beans.beancontext provide the support for creating JavaBeans

• There is no JavaBean superclass that all JavaBeans extend and no interface that all JavaBeans implement

• Creating a class of JavaBeans largely involves adhering to the standards of the JavaBeans component model

Page 7: Chapter 8: JavaBeans

What Makes a Class a Bean

Some of the main characteristics of JavaBeans follow:– If a bean has a property names X, it can have

public methods named setX or getX, to assign and return the value of the property

– If a bean can generate events of the class Yevent, it should have public methods of the following forms:

void addYListener( YEvent )

void removeYListener( Yevent )

Page 8: Chapter 8: JavaBeans

What Makes a Class a Bean

Other public methods of the class are actions that the JavaBean can execute– All beans should have a constructor that takes no arguments

because most beanboxes call this constructor– A JavaBean class must implement the marker interface

Serializable because beanboxes use serialization to save the state of beans

Page 9: Chapter 8: JavaBeans

Bean Development Environments

• Sun created a demonstration development environment called the BeanBox

• When using the BeanBox, keep in mind that it is not a production IDE and that you should not use it to create JavaBean applications

• Instead, you should perform production development using tools such as IBM VisualAge for Java

• You can load beans into the Sun BeanBox directly from a .jar file

Page 10: Chapter 8: JavaBeans

Bean Development Environments

• In general, a beanbox uses the classes of the java.lang.reflect package to analyze the classes contained within the .jar file

• If the beanbox finds public methods of the form setX, getX, or isX, it assumes that X is a property of the JavaBean

• If the beanbox finds public methods of the form addYListener and removeYListener, both of which return void and take a single argument of type Yevent, it assumes that the JavaBean fires events of the class YEvent

Page 11: Chapter 8: JavaBeans

Using the Sun BeanBox

To start the BeanBox:

1. Open a command-line window and go to the folder in which you installed the BDK

2. Make the subfolder beanbox the current folder

3. Enter run

Page 12: Chapter 8: JavaBeans

Using the Sun BeanBox

To position a demonstration bean in the Composition window:

1. Select the OrangeButton bean from the Toolbox window by clicking the word OrangeButton with the mouse

2. Position the cross-hair cursor on the BeanBox window. Click the BeanBox window, and the OrangeButton bean drops into place

3. Try changing some properties. Click the background box in the Properties window

Page 13: Chapter 8: JavaBeans

Using the Sun BeanBox

4. Change the color of the bean by selecting a color from the drop-down list on the right of the window or by change the red, green, or blue intensity values in the middle of the window

To remove the bean from the BeanBox window:1. Make sure the bean is selected

2. Click Edit from the BeanBox menu bar, and then click Cut

3. Click File from the BeanBox menu bar, and then click Exit to close the BeanBox window

Page 14: Chapter 8: JavaBeans

Using the Sun BeanBox

When a bean is instantiated in a beanbox, the bean’s methods are called in the following order:

1 The constructor with no arguments is called to set up the bean

2 The preferredSize method, which you encounter again later in this unit, returns the display dimensions of the bean

3 The paint method draws the bean on the BeanBox window

Page 15: Chapter 8: JavaBeans

Creating a JavaBean Class

• An example JavaBean is developed throughout this unit

• The bean displays an image on a panel

• The first version is a class called ImageBean1

• It extends the class Panel and manipulates an object of type Image

Page 16: Chapter 8: JavaBeans

Creating a JavaBean Class

The ImageBean1 bean has three properties:

1 The properties fileName and fillColor have mutator methods setFileName and setFillColor, and accessor methods getFileName and getFillColor. They are read-write properties

2 ImageBean1 has a getPreferredSize method but no setPreferredSize method. The property preferredSize is a read-only property of the bean

Page 17: Chapter 8: JavaBeans

Breakdown of the ImageBean1 Class

• The ImageBean1 class uses the JPanel class in the package javax.swing, several classes in the packages java.awt and java.io, as well as the ImageObserver class in the package java.awt.image as shown on page 700

• The class ImageBean1 inherits its serialization behavior from its superclass, JPanel

• Therefore, ImageBean1 does not have to declare explicitly that it implements the interface Serializable as shown on page 700

Page 18: Chapter 8: JavaBeans

Breakdown of the ImageBean1 Class

• The fields of the ImageBean1 class record the state of the JavaBean

• The imageUpdate method is part of the ImageObserver interface that all AWT components implement

• When a method is called to draw an image, the method may return before the image is fully available

Page 19: Chapter 8: JavaBeans

ImageBean1 Class Used in a Beanbox

• Before you can access a JavaBean in a beanbox, you must put it in a .jar file

• The .jar file must include a manifest that specifies which .class files in the .jar file are JavaBeans

To load this example bean into the BeanBox window of the BDK:

1. Create a minimal manifest file for the bean ImageBean1. In a text editor, create a flat text file that contains the following two lines(as shown on page 703), followed by a blank line

Page 20: Chapter 8: JavaBeans

ImageBean1 Class Used in a Beanbox

2. Save the file with filename ImageBean.manifest in the folder that is the parent of the folder that contains the package examples

3. Make sure the current folder is the one that contains the file ImageBeans.manifest and the examples folder

4. Copy the file ImageBeans.jar into the jars subfolder of the folder in which you installed the BDK

5. To start the beanbox, make the subfolder beanbox the current folder, and enter the command run

6. Using the same method described earlier in this unit, load the ImageBean1 bean into the BeanBox

Page 21: Chapter 8: JavaBeans

ImageBean1 Class Used in a Beanbox

7. Select the ImageBean1 bean from the Toolbox window by clicking the word ImageBean1 with the mouse

8. Position the cross-hair cursor on the BeanBox window. Click the BeanBox window, and the ImageBean1 bean drops into place

Page 22: Chapter 8: JavaBeans

ImageBean1 Class Used in a Beanbox

To tie a property from the JellyBean JavaBean to the ImageBean1 JavaBean:

1. The BeanBox ships a JellyBean JavaBean that has a color property. Select the JellyBean bean from the Toolbox window, and then drop the bean on the BeanBox composition window

2. The JellyBean should be surrounded by a hatched black and gray border to indicate it is selected

3. Click Edit on the menu bar of the BeanBox window, and then click Bind property

Page 23: Chapter 8: JavaBeans

ImageBean1 Class Used in a Beanbox

4. The PropertyNameDialog box appears

5. A red line appears. One end of the line is attached to the JellyBean and the other end follows the mouse

6. The PropertyNameDialog box appears again, now showing the properties of the ImageBean1 bean. Select fillColor, and click OK

Page 24: Chapter 8: JavaBeans

Indexed Properties

• Properties are not limited to individual values

• They can be indexed under a single name with an integer index value

• You can provide methods for reading and writing individual elements of the property

• Syntax

property_type getproperty_name ( int index )

void setproperty_name( property_type x, int index )

Page 25: Chapter 8: JavaBeans

Bound Properties

• Bound properties provide notification when they change so that other JavaBeans can listen for these changes and act accordingly

• The package java.beans includes a class for use with bound properties, PropertyChangeSupport, that is detailed next

• Class: java.beans.PropertyChangeSupport• Purpose: You can create an instance of this class

for a JavaBean class and delegate to it the tasks of maintaining a list of interested listeners and sending java.beans.PropertyChangeEvent objects

Page 26: Chapter 8: JavaBeans

Bound Properties

• Constructors:

PropertyChangeSupport( Object sourceBean )

• Methods:– void addPropertyChangeListener( PropertyChangeListener

listener )

– void firePropertyChange( String propertyName, Object oldValue, Object newValue

)

– void removePropertyChangeListener( PropertyChangeListener listener )

Page 27: Chapter 8: JavaBeans

Bound Properties

The next example program shows how these methods are used typically:– A class defines its own

addPropertyChangeListener and removePropertyCnageListener methods that do little more than pass the PropertyChangeListener parameter they receive along to the PropertyChangeSupport instance

– The set methods for the properties are modified to call the firePropertyChange method to indicate that the value has changed

Page 28: Chapter 8: JavaBeans

Constrained Properties

• The JavaBeans component model allows for the possibility that one or more of the listening objects might not allow some changes to the value of a property

• This variation is known as a constrained property

• To implement a constrained property, a JavaBean class should use a VetoablesChangeSupport object

• Class: java.beans.VetoableChangeSupport

Page 29: Chapter 8: JavaBeans

Constrained Properties

• Purpose: Use a VetoableChangeSupport object for constrained properties much like you use a PropertyChangeSupport object for bound properties

• Constructors:– VetoableChangeSupport( Object sourceBean )

• Methods:– void addVetoableChangeListener( PropertyChangeListener

listener )– void firePropertyChange( String propertyName, Object

oldValue, Object newValue )– void removeVetoableChangeListener( PropertyChangeListener

listener )

Page 30: Chapter 8: JavaBeans

Adding Custom Event Types

• JavaBeans are not limited to just the PropertyChangeEvent event type

To create and use a custom event:1. Define the event class that extends java.util.EventObject

or one of its subclasses

2. Define the interface, XListener, that the event listeners must implement. This interface should extend the marker interface java.util.EventListener

3. The JavaBean class should define a method, fireX, that goes through the list of registered listeners and calls the handleX method, passing an X object for each of them

Page 31: Chapter 8: JavaBeans

Creating a JavaBean Class With Events

• The second JavaBean class, ImageBean2, is an enhancement of the ImageBean1 class

• This class converts all the properties into bound properties and adds a custom event type, FillColorEvent

• In a beanbox, it is very simple to add a button JavaBean and then connect the button’s click action to one of these methods

Page 32: Chapter 8: JavaBeans

Breakdown of the ImageBean2 Class

• The two new fields support the handling of events

• The field myListeners provides the support for creating bound properties

• The field FillColorListeners is the list of listeners registered to receive FillColorEvent objects (as shown on page 715)

• The methods for accessing the properties have not changed, but the imageUpdate method has change to fire a PropertyChangeEvent if the image loaded has a size different from the previous image

Page 33: Chapter 8: JavaBeans

Custom Event Class for the ImageBean2 Bean

• A separate class defines the custom event used in the ImageBean2 class

• The constructor takes three inputs: a reference to the object that is the source of the event, an integer constant that is the event identifier, and the color associated with the event

• The source reference is passed along to the superclass constructor, Event Object

Page 34: Chapter 8: JavaBeans

Listener Interface for the Custom Event Class

• The last piece of code needed for this example is the definition of the FillColorListener interface

• It adds just one empty method to the EventListener interface:

package examples.beans;import java.util.EventListener;public interface FillColorListener extends EventListener {

/** The method called when a FillColor change occurs*/public void fillColorChange( FillColorEvent e ) ;

}

Page 35: Chapter 8: JavaBeans

ImageBean2 Used in a BeanBox

To load ImageBean2 into the BDK BeanBox:1. Add lines to the ImageBeans.manifest file in the folder

into which you unpacked the examples.jar file, so that the file lists both ImageBean1 and ImageBean2

2. Type the following command, on one line, from the parent folder of the examples folder to create a .jar file ImageBeans.jar as shown on page 719

3. Copy the file ImageBeans.jar into the jars subfolder of the folder in which you installed the BDK

4. Start the BeanBox. See that ImageBean2 is now listed in the Toolbox window

Page 36: Chapter 8: JavaBeans

ImageBean2 Used in a BeanBox

5. You can have a little fun with this bean. Drop an ImageBean2 bean onto the BeanBox window

6. Drop two BlueButton beans on to the BeanBox window and position them near, but not on top of, the ImageBean2. These beans look like buttons labeled “press”

7. Change the background property of one BlueButton to red and the other BlueButton to green

8. Click the red button. While it is selected, click Edit on the menu bar, and then select Events

9. Move over the area of the ImageBean2 bean, and click

Page 37: Chapter 8: JavaBeans

ImageBean2 Used in a BeanBox

10. The EventTargetDialog appears, inviting you to select a target method

11. Now, try clicking the red button. The fill color of the ImageBean2 should turn red

12. In a similar fashion, make the green button change the fill color of the ImageBean2 to green

13. Now, you can use the bound properties of the ImageBean2. Drop a JellyBean onto the BeanBox window

14. Select the ImageBean2. Click Edit from the menu bar and then click Bind property

15. Connect the red line from the ImageBean2 to the JellyBean

Page 38: Chapter 8: JavaBeans

Supplying Additional JavaBean Information

A beanbox finds the information classes as follows:– For each JavaBean class, the beanbox looks for a

class with a name formed by appending the suffix BeanInfo onto the name of the JavaBean class

– If a class satisfies the naming convention, the beanbox next checks whether the class implements the BeanInfo interface

– If a class satisfies these requirements, the beanbox can call its methods to collect detailed information about the JavaBean

Page 39: Chapter 8: JavaBeans

Supplying Additional JavaBean Information

Methods:– BeanInfo[ ] getAdditionalBeanInfo()

– BeanDescriptor getBeanDescriptor()

– int getDefaultEventIndex()

– int getDefaultPropertyIndex()

– EventSetDescriptor[ ] getEventSetDescriptors()

– Image getIcon( int iconKind )

– MethodDescriptor[ ] getMethodDescriptors()

– Property Descriptor[ ] getPropertyDescriptors()

Page 40: Chapter 8: JavaBeans

Supplying Additional JavaBean Information

• You can define a class that implements the BeanInfo interface and supply implementations of all the BeanInfo methods

• A simpler approach is to define a class that extends the class java.beans.SimpleBeanInfo

• You can extend the SimpleBeanInfo class and override selected methods

Page 41: Chapter 8: JavaBeans

Providing a Custom Property Editor

• Beanboxes can provide property editors for several different types of properties, including String, Font, and Color

• A programmer who creates JavaBeans must provide a property editor for other kinds of properties

• All property editors must implement the interface java.beans.PropertyEditor

• The class java.beans.PropertyEditorSupport provides a trivial property editor

• Beanboxes usually provide a dialog box containing a list of all the JavaBean properties and a field for editing each one

Page 42: Chapter 8: JavaBeans

Providing a Custom Property Editor

• A special purpose customizer can treat the JavaBean as a whole because it can understand the dependencies between fields and makes sure that they are respected– The class must implement the java.beans.Customizer

interface– An instance of the class must be an AWT component

that can be embedded in a dialog box– The class must have a constructor that has no

arguments• When you create a customizer class, you must also

provide the method getBeanDescriptor in the BeanInfo class associated with the JavaBean

Page 43: Chapter 8: JavaBeans

Creating a JavaBean Class With a BeanInfo Class

• The third version of the example JavaBean, the ImageBean3 class is expanded further by the addition of another property called scaling

• It allows the image to appear at its original size or scaled to fit the panel that contains it

• This property has only two allowable values, the constants ORIGINAL_SIZE and SCALED_TO_FIT, both of which are defined in the class

• ImageBean3 also has an accompanying BeanInfo class

Page 44: Chapter 8: JavaBeans

Breakdown of the ImageBean3 Class

• The ImageBean3 class is a variation on the ImageBean1 class that has a BeanInfo class

• The paintComponent method is changed to handle the choices of image scaling

• None of the other methods in the ImageBean3 class are new or have been updated

• However, this class uses two additional classes:

– The property editor class

– The bean information class

Page 45: Chapter 8: JavaBeans

Property Editor Class for the ImageBean3 Class

• The scaling property of the ImageBean3 class requires a customized editor, and the ScalingEditor class provides it

• This simple property editor only needs to present a list of two choices for users

• Therefore, the ScalingEditor can be defined as a subclass of PropertyEditorSupport and can use most of the inherited method implementations

Page 46: Chapter 8: JavaBeans

Property Editor Class for the ImageBean3 Class

• The ScalingEditor class overrides three methods of the PropertyEditorSupport class that relate to the names and values of the allowable choices

• The getTags method returns the names of the value scaling for the property:

public String[ ] getTags( )

Page 47: Chapter 8: JavaBeans

Breakdown of the ImageBean3BeanInfo Class

• The first method of the class, getPropertyDescriptors, returns an array of objects in which each element describes a different property of the ImageBean3 class:

public class ImageBean3BeanInfo extends SimpleBeanInfo {

public PropertyDescriptor[ ] getPropertyDescriptors( ) {

• The method setPropertyEditorClass makes the association between the scaling property and its editor class

Page 48: Chapter 8: JavaBeans

More Breakdown of the ImageBean3BeanInfo Class

• The catch block is required to handle any errors that may occur because the introspection process could not be completed for the JavaBean

• This catch clause recovers by printing a message to the console and returning the default list of property descriptors, as determined by the superclass SimpleBeanInfo

• The other method in this BeanInfo class is used to indicate the default property for the JavaBean

Page 49: Chapter 8: JavaBeans

Creating a JavaBean Class That Uses the BeanContext API

• The fourth and final version of the example JavaBean, the ImageBean4 class, is expanded further using the BeanContext API to dynamically query its run-time environment to discover and use services offered by other JavaBeans

• The BeanContext API has two parts

• The first is a logical containment hierarchy for JavaBeans that describes JavaBeans as being located within something called a BeanContext container

Page 50: Chapter 8: JavaBeans

Creating a JavaBean Class That Uses the BeanContext API

• In the case if the ImageBean4 example, the BeanContext container is the BeanBox itself

• To take advantage of the fact that it contains BeanContext, a JavaBean must implement the BeanContextChild interface or implement the BeanContextProxy interface

• A JavaBean that implements the BeanContextProxy acts as a proxy for the object that does implement the BeanContextChild interface

Page 51: Chapter 8: JavaBeans

Creating a JavaBean Class That Uses the BeanContext API

• ImageBean4 imports the contents of the java.beans.beancontext packages

• ImageBean4 implements the BeanContextProxy interface which has only a single method, getBeanContextProxy, which returns an object that implements the BeanContextChild interface

• One field is added, and that is an object of the ImageBeanContextChildSupport class that will provide the support for implementing the BeanContextChild interface on behalf of ImageBean4

Page 52: Chapter 8: JavaBeans

Creating a JavaBean Class That Uses the BeanContext API

• One method is added, and that is the one method of the BeanContextProxy interface, getBeanContextProxy

• It is written to return the ImageBeanContextChildSupport object

• The if statement found at the beginning of this method is put at the beginning of each method in the ImageBean4 class to enable the tracing of the method

• The test that protects the call to getMethodTracer is required in case the method tracing service could not be provided for some reason

Page 53: Chapter 8: JavaBeans

Context Child Support Class for the ImageBean4 Class

• Most of the work done to use the BeanContext API is found in the ImageBeanChildContextSupport class

• The complete source code for the ImageBeanChildContextSupport class is shown on pages 738-740

Page 54: Chapter 8: JavaBeans

Breakdown of the ImageBeanContextChildSupport Class

• The support for method tracing provided by the BeanBox is implemented in a demonstration class that is included with the BDK in the file methodtracer.jar

• This .jar file must be added to the CLASSPATH environment variable in order to be able to successfully compile this class:import sunw.demo.methodtracer.MethodTracer ;

• This class extends the class BeanContextChildSupport that is part of java.beans.beancontext package

Page 55: Chapter 8: JavaBeans

More Breakdown of the ImageBeanContextChildSupport Class

• The releaseBeanContextServices method overrides the method inherited from BeanContextChildSupport

• The serviceAvailable method is part of the BeanContextServicesListener interface and is called when a service becomes available

• To load the ImageBean4 JavaBean into the BDK BeanBox, follow the same process you used for ImageBean1, ImageBean2, and ImageBean3

Page 56: Chapter 8: JavaBeans

Enterprise JavaBeans

• The Enterprise JavaBeans(EJB) specification describes a model for Java components that is designed to be installed on and made available from servers

• The connection between EJB components and JavaBeans is that both are component models for the Java programming language

• The EJB specification does not include the same programming conventions listed in Table 15-2 for JavaBeans

Page 57: Chapter 8: JavaBeans

Enterprise JavaBeans

• EJB components are components intended for use in the multi-tier networks of large enterprises that need a specification for sharing objects between many systems

• An EJB component does not use any system-level services directly and does not have a user interface

• EJB components contain only the logic required to run business processes

• Typically, they are made available from a server called an application server

Page 58: Chapter 8: JavaBeans

Enterprise JavaBeans

• On the application server, EJB components are located within an EJB container

• The container handles all the details of creating, activating, and destroying EJB component instances

• It also deals with the complex issues related to transactions and security

• The great advantage of EJBs over other distributed programming frameworks is that EJB developers focus on the business logic and are relieved of responsibility for difficult tasks, such as ensuring the integrity of transactions

Page 59: Chapter 8: JavaBeans

Unit Summary

• The JavaBeans component model is a framework for creating reusable Java classes

The following facts are key to understanding this unit:

• The interface to a JavaBean consists of methods, properties, and events

• The package java.beans provides the core classes and interfaces that support beans

Page 60: Chapter 8: JavaBeans

Unit Summary

• A bean must implement the interface java.ioSerializable because beanboxes use object serialization

• Properties are the attributes of a bean, commonly implemented as the fields of a Java class

• Bound properties can notify other beans when their value changes

• Constrained properties are bound properties with the additional characteristic that other listeners can prevent a change in value from occurring

Page 61: Chapter 8: JavaBeans

Unit Summary

• Event handling follows the same model as event handling for components in the Swing and AWT APIs

• Changes to properties trigger events of the class PropertyChangeEvent objects

• If the Reflection API cannot provide all the information that a beanbox needs about a bean, you can supply an additional information class that implements the interface BeanInfo

• Beanboxes provide property editors for String, Font, and Color properties

Page 62: Chapter 8: JavaBeans

Unit Summary

• If the property editor dialog box of the beanbox is not adequate, you can supply a customizer class for the bean

• By using the BeanContext API, a JavaBean object dynamically queries its runtime environment to discover and use services offered by other JavaBeans

• The Enterprise JavaBeans specification defines a model for components that are located on a server and shared across networks