Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Introduction to JavaBeans

JavaBeans are reusable, platform-independent components in Java that encapsulate multiple objects into a single object, allowing for easier application development. They must follow specific conventions, such as having a no-argument constructor and being serializable, and can be manipulated visually using builder tools. JavaBeans support properties, methods, events, and persistence, enabling developers to create dynamic and customizable components that can be reused across different environments.

Uploaded by

kusumakumarchegg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introduction to JavaBeans

JavaBeans are reusable, platform-independent components in Java that encapsulate multiple objects into a single object, allowing for easier application development. They must follow specific conventions, such as having a no-argument constructor and being serializable, and can be manipulated visually using builder tools. JavaBeans support properties, methods, events, and persistence, enabling developers to create dynamic and customizable components that can be reused across different environments.

Uploaded by

kusumakumarchegg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

JAVA BEANS

Introduction
One of the most important topics in software component model is reusability. Writing self-contained
software under the moto of “Developed them once, run and reuse them everywhere” is most required
and appreciated. So reusability is added into the Java programming language with the help of
JavaBeans.

JavaBeans
“A JavaBean is reusable, platform independent component that can be manipulated visually in a
builder tool.”

In computing, based on the Java Platform, JavaBeans are classes that encapsulate many objects into a
single object (the bean). Builder tool enables you to create and use beans for application
development purpose.

In simple words JavaBean is nothing but a Java class. When these JavaBeans are used in other
applications, the internal workings of such components are hidden from the application developer.

A JavaBean is a Java class that should follow the following conventions:

• It should have a no-argument constructor.


• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and
setter methods.

A “Bean” is a reusable software component model based on sun’s java bean specification that can be
manipulated visually in a builder tool.

The term software component model describes how to create and use reusable software components
to build an application.

Builder tool is nothing but an application development tool which lets you both to create new beans or
use existing beans to create an application.

To enrich the software systems by adopting component technology JAVA came up with the concept
called Java Beans.

Java provides the facility of creating some user defined components by means of Bean programming.

We create simple components using java beans.

We can directly embed these beans into the software.

Example:

All Swing and AWT classes are JavaBeans. GUI components are ideal JavaBeans.
Components of JavaBeans

The classes that contained definition of beans is known as components of JavaBeans. These classes
follow certain design conventions. It includes properties, events, methods and persistence. There are
two types of components, GUI based and non GUI based.

Properties (data members): Property is a named attribute of a bean; it includes color, label, font,
font size, display size. It determines appearance, behavior and state of a bean.

Methods: Methods in JavaBeans are same as normal Java methods in a class. It doesn’t follow any
specific naming conventions. All properties should have accessor and getter methods.

Events: Events in JavaBeans are same as SWING/AWT event handling.

Persistence: Serializable interface enables JavaBean to store its state.

JavaBean component

JavaBeans Properties

JavaBean property can be access by the user of the object; it can be read, write, read only or write
only.

We can access these JavaBeans properties with the help of getPropertyName () method also known as
getter or accessor and setPropertyName () method known as setter written in implementation class of
bean.

getPropertyName (): For example, if property name is Title, your method name would be getTitle().
setPropertyName (): For example, if property name is Title, your method name would be setTitle().
Example of JavaBeans

Before going to write a JavaBean, here are some basic rules. A JavaBean should be public, should has
no argument default constructor and should implement serializable interface. Keep these basic rules
in mind before writing a JavaBean.

public class BankAccount implements java.io.Serializable {


private String accountNumber = null;
private String totalAmount = null;
private String accountHolderName = null;
private int accountHolderAge = 0;
private String accountHolderAddress = null;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public int getAccountHolderAge() {
return accountHolderAge;
}
public void setAccountHolderAge(int accountHolderAge) {
this.accountHolderAge = accountHolderAge;
}
public String getAccountHolderAddress() {
return accountHolderAddress;
}
public void setAccountHolderAddress(String accountHolderAddress) {
this.accountHolderAddress = accountHolderAddress;
}
}
Example of JavaBean class

public class Employee implements java.io.Serializable


{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}

How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

Advantages of JavaBeans

Following are some advantages of JavaBeans:

• Reusability in different environments.


• Used to create applet, servlet, application or other components.
• JavaBeans are dynamic, can be customized.
• Can be deployed in network systems
• The java beans possess the property of “Write once and run anywhere”.
• Beans can work in different local platforms.
• Beans have the capability of capturing the events sent by other objects and vice versa
• Enabling object communication.
• The properties, events and methods of the bean can be controlled by the application
developer. (ex. Add new properties)
• Beans can be configured with the help of auxiliary software during design time.(no hassle
at runtime)
• The configuration setting can be made persistent.(reused)
• Configuration setting of a bean can be saved in persistent storage and restored later.
Definition of a builder tool:

Builder tools allow a developer to work with JavaBeans in a convenient way. By examining a
JavaBean by a process known as Introspection, a builder tool exposes the discovered features of
the JavaBean for visual manipulation.

A builder tool maintains a list of all JavaBeans available. It allows you to compose the Bean into
applets, application, servlets and composite components (e.g. a JFrame), customize its behavior
and appearance by modifying its properties and connect other components to the event of the
Bean or vice versa.

Examples:

Java Workshop2.0
Visual age for java
Jbuilder
Beans Development Kit

Introspection
Introspection is the process of analyzing a Bean to determine its capabilities. This is an essential
feature of the Java Beans API, because it allows an application builder tool to present information
about a component to a software designer. Without introspection, the Java Beans technology could
not operate.

At runtime and in the builder environment we need to be able to figure out which properties, events,
and methods a Java Bean supports. We call this process introspection.

There are two ways in which the developer of a Bean can indicate which of its properties, events, and
methods should be exposed by an application builder tool.

• With the first method, simple naming conventions are used. These allow the introspection
mechanisms to infer information about a Bean.

• In the second way, an additional class is provided that explicitly supplies this information.

The following sections indicate the design patterns for properties and events that enable the
functionality of a Bean to be determined.

Design Patterns for Properties

A property is a subset of a Bean’s state. The values assigned to the properties determine the behavior
and appearance of that component. This section discusses three types of properties: simple, Boolean,
and indexed.

Simple Properties

A simple property has a single value. It can be identified by the following design patterns, where N is
the name of the property and T is its type.

public T getN( );
public void setN(T arg);

A read/write property has both of these methods to access its values. A read-only property has only a
get method. A write-only property has only a set method. The following listing shows a class that has
three read/write simple properties:
public class Box {
private double depth, height, width;
public double getDepth( ) {
return depth;
}
public void setDepth(double d) {
depth = d;
}
public double getHeight( ) {
return height;
}
public void setHeight(double h) {
height = h;
}
public double getWidth( ) {
return width;
}
public void setWidth(double w) {
width = w;
}
}

Boolean Properties

A Boolean property has a value of true or false. It can be identified by the following design patterns,
where N is the name of the property:

public boolean isN( );


public boolean getN( );
public void setN(boolean value);

Either the first or second pattern can be used to retrieve the value of a Boolean property. However, if
a class has both of these methods, the first pattern is used. The following listing shows a class that has
one Boolean property:

public class Line {


private boolean dotted = false;
public boolean isDotted( ) {
return dotted;
}
public void setDotted(boolean dotted) {
this.dotted = dotted;
}
}

Indexed Properties

An indexed property consists of multiple values. It can be identified by the following design patterns,
where N is the name of the property and T is its type:

public T getN(int index);


public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);

The following listing shows a class that has one read/write indexed property:
public class PieChart {
private double data[ ];
public double getData(int index) {
return data[index];
}
public void setData(int index, double value) {
data[index] = value;
}
public double[ ] getData( ) {
return data;
}
public void setData(double[ ] values) {
data = values;
}
}

Bound Properties

Bound properties support the PropertyChangeListener class.

Sometimes when a Bean property changes, another object might need to be notified of the change,
and react to the change. Whenever a bound property changes, notification of the change is sent to
interested listeners.

The accessor methods for a bound property are defined in the same way as those for simple
properties, however, you also need to provide the event listener registration methods for
PropertyChangeListener classes and fire a PropertyChangeEvent event to
the PropertyChangeListener objects by calling their propertyChange methods.

The convenience PropertyChangeSupport enables your bean to implement these methods. Your
bean can inherit changes from the PropertyChangeSupport class, or use it as an inner class.

In order to listen for property changes, an object must be able to add and remove itself from the
listener list on the bean containing the bound property. It must also be able to respond to the event
notification method that signals a property change.

The PropertyChangeEvent class encapsulates property change information, and is sent from the
property change event source to each object in the property change listener list with
the propertyChange method.

Implementing Bound Property Support within a Bean

To implement a bound property in your application, follow these steps:

1. Import the java.beans package. This gives you access to the PropertyChangeSupport class.
2. Instantiate a PropertyChangeSupport object. This object maintains the property change
listener list and fires property change events. You can also make your class
a PropertyChangeSupport subclass.
3. Implement methods to maintain the property change listener list. Since
a PropertyChangeSupport subclass implements these methods, you merely wrap calls to the
property-change support object's methods.
4. Modify a property's set method to fire a property change event when the property is changed.

A bound property notifies listeners when its value changes. This has two implications:
1. The bean class includes addPropertyChangeListener() and removePropertyChangeListener()
methods for managing the bean's listeners.
2. When a bound property is changed, the bean sends a PropertyChangeEvent to its registered
listeners.
PropertyChangeEvent and PropertyChangeListener live in the java.beans package.

The java.beans package also includes a class, PropertyChangeSupport, that takes care of most of
the work of bound properties. This handy class keeps track of property listeners and includes a
convenience method that fires property change events to all registered listeners.

The following example shows how you could make the mouthWidth property a bound property
using PropertyChangeSupport. The necessary additions for the bound property are shown in bold.

import java.beans.*;

public class FaceBean {


private int mMouthWidth = 90;
private PropertyChangeSupport mPcs =
new PropertyChangeSupport(this);

public int getMouthWidth() {


return mMouthWidth;
}

public void setMouthWidth(int mw) {


int oldMouthWidth = mMouthWidth;
mMouthWidth = mw;
mPcs.firePropertyChange("mouthWidth",
oldMouthWidth, mw);
}

public void
addPropertyChangeListener(PropertyChangeListener listener) {
mPcs.addPropertyChangeListener(listener);
}

public void
removePropertyChangeListener(PropertyChangeListener listener) {
mPcs.removePropertyChangeListener(listener);
}
}

Bound properties can be tied directly to other bean properties using a builder tool like NetBeans. You
could, for example, take the value property of a slider component and bind it to
the mouthWidth property shown in the example. NetBeans allows you to do this without writing any
code.
Constrained Properties

A bean property is constrained if the bean supports the VetoableChangeListener


and PropertyChangeEvent classes, and if the set method for this property throws
a PropertyVetoException.

Constrained properties are more complicated than bound properties because they also support
property change listeners which happen to be vetoers.

The following operations in the setXXX method for the constrained property must be implemented in
this order:

1. Save the old value in case the change is vetoed.


2. Notify listeners of the new proposed value, allowing them to veto the change.
3. If no listener vetoes the change (no exception is thrown), set the property to the new value.

The accessor methods for a constrained property are defined in the same way as those for simple
properties, with the addition that the setXXX method throws a PropertyVetoException exception.
The syntax is as follows:
public void setPropertyName(PropertyType pt)
throws PropertyVetoException {code}

Handling Vetoes

If a registered listener vetoes a proposed property change by throwing


a PropertyVetoException exception, the source bean with the constrained property is responsible for
the following actions:

• Catching exceptions.
• Reverting to the old value for the property.
• Issuing a new VetoableChangeListener. vetoableChange call to all listeners to report the
reversion.

The VetoableChangeListener class throws a PropertyVetoException and handles


the PropertyChangeEvent event fired by the bean with the constrained property.

The VetoableChangeSupport provides the following operations:

• Keeping track of VetoableChangeListener objects.


• Issuing the vetoableChange method on all registered listeners.
• Catching any vetoes (exceptions) thrown by listeners.
• Informing all listeners of a veto by calling vetoableChange again, but with the old property
value as the proposed "new" value.

A constrained property is a special kind of bound property. For a constrained property, the bean keeps
track of a set of veto listeners. When a constrained property is about to change, the listeners are
consulted about the change. Any one of the listeners has a chance to veto the change, in which case
the property remains unchanged.

The veto listeners are separate from the property change listeners. Fortunately,
the java.beans package includes a VetoableChangeSupport class that greatly simplifies constrained
properties.

Changes to the mouthWidth example are shown in bold:

import java.beans.*;
public class FaceBean {
private int mMouthWidth = 90;
private PropertyChangeSupport mPcs = new PropertyChangeSupport(this);
private VetoableChangeSupport mVcs = new VetoableChangeSupport(this);

public int getMouthWidth() {


return mMouthWidth;
}

public void setMouthWidth(int mw) throws PropertyVetoException {


int oldMouthWidth = mMouthWidth;
mVcs.fireVetoableChange("mouthWidth",oldMouthWidth, mw);
mMouthWidth = mw;
mPcs.firePropertyChange("mouthWidth",oldMouthWidth, mw);
}

public void addPropertyChangeListener(PropertyChangeListener listener) {


mPcs.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {


mPcs.removePropertyChangeListener(listener);
}

public void addVetoableChangeListener(VetoableChangeListener listener) {


mVcs.addVetoableChangeListener(listener);
}

public void removeVetoableChangeListener(VetoableChangeListener listener) {


mVcs.removeVetoableChangeListener(listener);
}
}

The main difference resides in the fact that PropertyChangeListener are applied to bound properties
while VetoableChangeListener are applied to constrained properties.

A bound property is just a property, while a constrained property is a property on which listeners
can express themselves about a change that is going to be made: they can refuse this change from
happening.

What it actually happens is that when you notify a vetoable property change you will do something
like

VetoableChangeSupport vcs;
vcs.fireVetoableChange(...);

and this can throw a PropertyVetoException which will tell your bean that an observer wishes to
block this property change (it should be rolled back).

Design Patterns for Events

Beans can generate events and send them to other objects. These can be identified by the following
design patterns, where T is the type of the event:

public void addTListener(TListener eventListener);


public void addTListener(TListener eventListener) throws TooManyListeners;
public void removeTListener(TListener eventListener);
These methods are used by event listeners to register an interest in events of a specific type.

The following listing outlines a class that notifies other objects when a temperature value moves
outside a specific range.

The two methods indicated here allow other objects that implement the TemperatureListener
interface to receive notifications when this occurs.

public class Thermometer {


public void addTemperatureListener(TemperatureListener tl) {
...
}
public void removeTemperatureListener(TemperatureListener tl) {
...
}
}

Design Patterns for Methods

Design patterns are not used for naming non property methods. The introspection mechanism finds all
of the public methods of a Bean. Protected and private methods are not presented.

The BeanInfo Interface

BeanInfo is an interface implemented by a class that provides explicit information about a Bean. It is
used to describe one or more feature sets of a Bean, including its properties, methods, and events.

You can explicitly expose a Bean's features in a separate, associated class that implements
the BeanInfo interface. By associating a BeanInfo class with your Bean, you can:

• Expose only those features you want to expose.


• Rely on BeanInfo to expose some Bean features while relying on low-level reflection to expose
others.
• Associate an icon with the target Bean.
• Specify a customizer class.
• Segregate features into normal and expert categories.
• Provide a more descriptive display name, or additional information about a Bean feature.

BeanInfo defines methods that return descriptors for each property, method, or event that you want
exposed. Here are the prototypes for these methods:

PropertyDescriptor[] getPropertyDescriptors();
MethodDescriptor[] getMethodDescriptors();
EventSetDescriptor[] getEventSetDescriptors();

Each of these methods returns an array of descriptors for each feature.

Feature Descriptors

BeanInfo classes contain descriptors that precisely describe the target Bean's features. The BDK
implements the following descriptor classes:

• FeatureDescriptor is the base class for the other descriptor classes. It declares the aspects
common to all descriptor types.
• BeanDescriptor describes the target Bean's class type and name, and describes the target
Bean's customizer class if it exists.

• PropertyDescriptor describes the target Bean's properties.

• IndexedPropertyDescriptor is a subclass of PropertyDescriptor, and describes the target Bean's


indexed properties.

• EventSetDescriptor describes the events the target Bean fires.

• MethodDescriptor describes the target Bean's methods.

• ParameterDescriptor describes method parameters.

The BeanInfo interface declares methods that return arrays of the above descriptors.

Creating a BeanInfo Class

This section uses the ExplicitButtonBeanInfo demo class to illustrate creating a BeanInfo class. Here
are the general steps to make a BeanInfo class:

1. Name your BeanInfo class. You must append the string "BeanInfo" to the target class name. If
the target class name is ExplicitButton, then its associated Bean information class must be
named ExplicitButtonBeanInfo

2. Subclass SimpleBeanInfo. This is a convenience class that implements BeanInfo methods to


return null, or an equivalent no-op value.

public class ExplicitButtonBeanInfo extends SimpleBeanInfo {

Using SimpleBeanInfo saves you from implementing all the BeanInfo methods; you only have to
override those methods you need.

3. Override the appropriate methods to return the properties, methods, or events that you want
exposed. ExplicitButtonBeanInfo overrides the getPropertyDescriptors() method to return four
properties:

public PropertyDescriptor[] getPropertyDescriptors() {


try {
PropertyDescriptor background = new PropertyDescriptor("background", beanClass);
PropertyDescriptor foreground = new PropertyDescriptor("foreground", beanClass);
PropertyDescriptor font = new PropertyDescriptor("font", beanClass);
PropertyDescriptor label = new PropertyDescriptor("label", beanClass);

background.setBound(true);
foreground.setBound(true);
font.setBound(true);
label.setBound(true);

PropertyDescriptor rv[] = {background, foreground, font, label};


return rv;
} catch (IntrospectionException e) {
throw new Error(e.toString());
}
}
There are two important things to note here:

• If you leave a descriptor out, that property, event or method will not be exposed. In other
words, you can selectively expose properties, events, or methods by leaving out those you
don't want exposed.

• If a feature's getter (for example, getMethodDescriptor()) method returns null, low-level


reflection is then used for that feature. This means, for example, that you can explicitly
specify properties, and let low-level reflection discover the methods. If you don't override
the SimpleBeanInfo default method, which returns null, low-level reflection will be used for
that feature.

Bean Persistence

A bean has the property of persistence when its properties, fields, and state information are saved to
and retrieved from storage. Component models provide a mechanism for persistence that enables the
state of components to be stored in a place for later retrieval.

The mechanism that makes persistence possible is called serialization. Object serialization means
converting an object into a data stream and writing it to storage.

Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization. The
object is then restored to its original state.

For example, a Java application can serialize a Frame window on a Microsoft Windows machine, the
serialized file can be sent with e-mail to a Solaris machine, and then a Java application can restore
the Frame window to the exact state which existed on the Microsoft Windows machine.

All beans must persist. To persist, your beans must support serialization by implementing either
the java.io.Serializable interface, or the java.io.Externalizable interface.

These interfaces offer you the choices of automatic serialization and customized serialization. If any
class in a class's inheritance hierarchy implements Serializable or Externalizable, then that class is
serializable.

Automatic Persistence: Automatic persistence are java’s built-in serialization mechanism to save and
restore the state of a bean.

External Persistence: External persistence, on the other hand, gives you the option of supplying your
own custom classes to control precisely how a bean state is stored and retrieved.

Java Beans API


The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package.
This section provides a brief overview of its contents.
Interface Summary

Interface Description

This interface is designed to work in collusion with


AppletInitializer
java.beans.Beans.instantiate.

Use the BeanInfo interface to create a BeanInfo class and provide


BeanInfo explicit information about the methods, properties, events, and
other features of your beans.

A customizer class provides a complete custom GUI for customizing a


Customizer
target Java Bean.

This interface is intended to be implemented by, or delegated from,


instances of java.beans.beancontext.BeanContext, in order to
DesignMode propagate to its nested hierarchy of
java.beans.beancontext.BeanContextChild instances, the current
"designTime" property.

ExceptionListener An ExceptionListener is notified of internal exceptions.

A "PropertyChange" event gets fired whenever a bean changes a


PropertyChangeListener
"bound" property.

A PropertyEditor class provides support for GUIs that want to allow


PropertyEditor
users to edit a property value of a given type.

A VetoableChange event gets fired whenever a bean changes a


VetoableChangeListener
"constrained" property.

Under some circumstances a bean may be run on servers where a GUI


Visibility
is not available.
Class Summary

Class Description

A BeanDescriptor provides global information about a "bean",


BeanDescriptor
including its Java class, its displayName, etc.

Beans This class provides some general purpose beans control methods.

The DefaultPersistenceDelegate is a concrete implementation of the


DefaultPersistenceDelegate abstract PersistenceDelegate class and is the delegate used by
default for classes about which no information is available.

An Encoder is a class which can be used to create files or streams


Encoder that encode the state of a collection of JavaBeans in terms of their
public APIs.

The EventHandler class provides support for dynamically generating


EventHandler event listeners whose methods execute a simple statement involving
an incoming event object and a target object.

An EventSetDescriptor describes a group of events that a given Java


EventSetDescriptor
bean fires.

An Expression object represents a primitive expression in which a


Expression single method is applied to a target and a set of arguments to return
a result - as in "a.getFoo()".

The FeatureDescriptor class is the common baseclass for


FeatureDescriptor
PropertyDescriptor, EventSetDescriptor, and MethodDescriptor, etc.

An "IndexedPropertyChange" event gets delivered whenever a


IndexedPropertyChangeEvent component that conforms to the JavaBeans™ specification (a "bean")
changes a bound indexed property.
An IndexedPropertyDescriptor describes a property that acts like an
IndexedPropertyDescriptor array and has an indexed read and/or indexed write method to
access specific elements of the array.

The Introspector class provides a standard way for tools to learn


Introspector about the properties, events, and methods supported by a target
Java Bean.

A MethodDescriptor describes a particular method that a Java Bean


MethodDescriptor
supports for external access from other components.

The ParameterDescriptor class allows bean implementors to provide


additional information on each of their parameters, beyond the low
ParameterDescriptor
level type information provided by the java.lang.reflect.Method
class.

The PersistenceDelegate class takes the responsibility for expressing


PersistenceDelegate the state of an instance of a given class in terms of the methods in
the class's public API.

A "PropertyChange" event gets delivered whenever a bean changes a


PropertyChangeEvent
"bound" or "constrained" property.

A class which extends the EventListenerProxy specifically for adding


PropertyChangeListenerProxy
a PropertyChangeListener with a "bound" property.

This is a utility class that can be used by beans that support bound
PropertyChangeSupport
properties.

A PropertyDescriptor describes one property that a Java Bean exports


PropertyDescriptor
via a pair of accessor methods.

The PropertyEditorManager can be used to locate a property editor


PropertyEditorManager
for any given type name.

PropertyEditorSupport This is a support class to help build property editors.


This is a support class to make it easier for people to provide
SimpleBeanInfo
BeanInfo classes.

A Statement object represents a primitive statement in which a


Statement single method is applied to a target and a set of arguments - as
in "a.setFoo(b)".

A class which extends the EventListenerProxy specifically for adding


VetoableChangeListenerProxy
a VetoableChangeListener with a "constrained" property.

This is a utility class that can be used by beans that support


VetoableChangeSupport
constrained properties.

The XMLDecoder class is used to read XML documents created using


XMLDecoder
the XMLEncoder and is used just like the ObjectInputStream.

The XMLEncoder class is a complementary alternative to


the ObjectOutputStream and can used to generate a textual
XMLEncoder representation of a JavaBean in the same way that
the ObjectOutputStream can be used to create binary representation
of Serializable objects.

Exception Summary

Exception Description

IntrospectionException Thrown when an exception happens during Introspection.

A PropertyVetoException is thrown when a proposed change to a


PropertyVetoException
property represents an unacceptable value.

Annotation Types Summary


Annotation Type Description

An annotation on a constructor that shows how the parameters of


ConstructorProperties that constructor correspond to the constructed object's getter
methods.

Indicates that an attribute called "transient" should be declared with


the given value when the Introspector constructs
Transient
a PropertyDescriptor or EventSetDescriptor classes associated with
the annotated code element.

Developing a Simple Bean Using the BDK


This section presents an example that shows how to develop a simple Bean and connect it to other
components via the BDK.

Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that is filled
with a color. A color is chosen at random when the Bean begins execution.

A public method can be invoked to change it. Each time the mouse is clicked on the Bean, another
random color is chosen. There is one boolean read/write property that determines the shape.

The BDK is used to lay out an application with one instance of the Colors Bean and one instance of the
OurButton Bean. The button is labeled “Change.” Each time it is pressed, the color changes.

Create a New Bean

Here are the steps that you must follow to create a new Bean:

1. Create a directory for the new Bean.


2. Create the Java source file(s).
3. Compile the source file(s).
4. Create a manifest file.
5. Generate a JAR file.
6. Start the BDK.
7. Test.

The following sections discuss each of these steps in detail.

Create a Directory for the New Bean

You need to make a directory for the Bean. To follow along with this example, create
c:\bdk\demo\sunw\demo\colors. Then change to that directory.

Create the Source File for the New Bean

The source code for the Colors component is shown in the following listing. It is located in the file
Colors.java.
The getRectangular ( ) and setRectangular( ) methods provide access to the one property of this Bean.
The change( ) method calls randomColor( ) to choose a color and then calls repaint( ) to make the
change visible. Notice that the paint( ) method uses the rectangular and color variables to determine
how to present the Bean.

// A simple Bean.

import java.awt.*;
import java.awt.event.*;

public class Colors extends Canvas {


transient private Color color;
private boolean rectangular;

public Colors() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
change();
}
});
rectangular = false;
setSize(200, 100);
change();
}

public boolean getRectangular() {


return rectangular;
}

public void setRectangular(boolean flag) {


this.rectangular = flag;
repaint();
}

public void change() {


color = randomColor();
repaint();
}

private Color randomColor() {


int r = (int) (255 * Math.random());
int g = (int) (255 * Math.random());
int b = (int) (255 * Math.random());
return new Color(r, g, b);
}

public void paint(Graphics g) {


Dimension d = getSize();
int h = d.height;
int w = d.width;
g.setColor(color);
if (rectangular) {
g.fillRect(0, 0, w - 1, h - 1);
} else {
g.fillOval(0, 0, w - 1, h - 1);
}
}
}Compile the Source Code for the New Bean
Compile the source code to create a class file. Type the following:

javac Colors.java.

Create a Manifest File

You must now create a manifest file. First, switch to the c:\bdk\demo directory. This is the directory
in which the manifest files for the BDK demos are located. Put the source code for your manifest file
in the file colors.mft. It is shown here:

Name: sunw/demo/colors/Colors.class

Java-Bean: True

This file indicates that there is one .class file in the JAR file and that it is a Java Bean. Notice that the
Colors.class file is in the package sunw.demo.colors and in the subdirectory sunw\demo\colors relative
to the current directory.

Generate a JAR File

Beans are included in the ToolBox window of the BDK only if they are in JAR files in the directory
:\bdk\jars. These files are generated with the jar utility. Enter the following:

jar cfm ..\jars\colors.jar colors.mft sunw\demo\colors\*.class

This command creates the file colors.jar and places it in the directory c:\bdk\jars. (You may wish to
put this in a batch file for future use.)

Start the BDK

Change to the directory c:\bdk\beanbox and type run. This causes the BDK to start. You should see
three windows, titled ToolBox, BeanBox, and Properties. The ToolBox window should include an entry
labeled “Colors” for your new Bean.

Create an Instance of the Colors Bean

After you complete the preceding steps, create an instance of the Colors Bean in the BeanBox
window. Test your new component by pressing the mouse anywhere within its borders. Its color
immediately changes. Use the Properties window to change the rectangular property from false to
true. Its shape immediately changes.

Create and Configure an Instance of the OurButton Bean

Create an instance of the OurButton Bean in the BeanBox window. Then follow these steps:

1. Go to the Properties window and change the label of the Bean to “Change”. You should see
that the button appearance changes immediately when this property is changed.

2. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed.
3. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.

4. The dialog box allows you to choose a method that should be invoked when this button is
clicked. Select the entry labeled “change” and click the OK button. You should see a message
box appear very briefly, stating that the tool is “Generating and compiling adaptor class.”

5. Click on the button. You should see the color change. You might want to experiment with the
Colors Bean a bit before moving on.

You might also like