Introduction to JavaBeans
Introduction to JavaBeans
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 “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.
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.
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.
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
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.
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:
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:
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:
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
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.
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 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
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:
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
• Catching exceptions.
• Reverting to the old value for the property.
• Issuing a new VetoableChangeListener. vetoableChange call to all listeners to report the
reversion.
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.
import java.beans.*;
public class FaceBean {
private int mMouthWidth = 90;
private PropertyChangeSupport mPcs = new PropertyChangeSupport(this);
private VetoableChangeSupport mVcs = new VetoableChangeSupport(this);
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).
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:
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.
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.
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:
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();
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.
The BeanInfo interface declares methods that return arrays of the above descriptors.
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
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:
background.setBound(true);
foreground.setBound(true);
font.setBound(true);
label.setBound(true);
• 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.
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.
Interface Description
Class Description
Beans This class provides some general purpose beans control methods.
This is a utility class that can be used by beans that support bound
PropertyChangeSupport
properties.
Exception Summary
Exception Description
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.
Here are the steps that you must follow to create a 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.
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 Colors() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
change();
}
});
rectangular = false;
setSize(200, 100);
change();
}
javac Colors.java.
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.
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:
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.)
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.
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 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.