You are on page 1of 20

Chapter-05 JavaBeans

Chapter -05

JavaBeans
5.1 Working with Java Beans:
In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single
object (the bean).

1. It should be serializable and implement the Serializable interface.


2. It provides a default, no-argument constructor.
3. It may have only private field variable.
4. They are serializable, have a zero-argument constructor
5. It may have a number of "getter" and "setter" methods for the properties.
6. A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.
7. Reusable software components can be simple like familiar push buttons, text fields list boxes,
scrollbars, dialogs.

Advantages:
 A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
 The properties, events, and methods of a Bean that are exposed to another application can be
controlled.
 The configuration settings of a Bean can be saved in persistent storage and restored at a later time.
 A Bean may register to receive events from other objects and can generate events that are sent to
other objects.

JavaBeans Features:
Main Components of JavaBeans:

 Introspection[naming convention and BeanInfo]

 Bound and Constraints

 Persistence

 Customizers

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 1 | 20


Chapter-05 JavaBeans

5.2 Introspection:
Introspection is the automatic process of analysing a bean's design patterns to reveal the bean's properties,
events, and methods.

Methods

Properties
Introspector

Events

This process controls the publishing and discovery of bean operations and properties. This lesson explains
the purpose of introspection, introduces the Introspection API, and gives an example of introspection code.

Purpose of Introspection:
A growing number of Java object repository sites exist on the Internet in answer to the demand for
centralized deployment of applets, classes, and source code in general. Any developer who has spent time
hunting through these sites for licensable Java code to incorporate into a program has undoubtedly struggled
with issues of how to quickly and cleanly integrate code from one particular source into an application.

The way in which introspection is implemented provides great advantages, including:

1. Portability - Everything is done in the Java platform, so you can write components once, reuse them
everywhere. There are no extra specification files that need to be maintained independently from
your component code. There are no platform-specific issues to contend with. Your component is not
tied to one component model or one proprietary platform. You get all the advantages of the evolving
Java APIs, while maintaining the portability of your components.

2. Reuse - By following the JavaBeans design conventions, implementing the appropriate interfaces,
and extending the appropriate classes, you provide your component with reuse potential that possibly
exceeds your expectations.

Introspection API:

The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection.

The Bean Info interface of the java.Beans package defines a set of methods that allow bean implementors to
provide explicit information about their beans. By specifying BeanInfo for a bean component, a developer
can hide methods, specify an icon for the toolbox, provide descriptive names for properties, define which
properties are bound properties, and much more.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 2 | 20


Chapter-05 JavaBeans
The getBeanInfo of the Introspector class can be used by builder tools and other automated environments to
provide detailed information about a bean. The getBeanInfo method relies on the naming conventions for the
bean's properties, events, and methods. A call to getBeanInfo results in the introspection process analyzing
the bean’s classes and superclasses.

The Introspector class provides Descriptor classes with information about properties, events, and methods
of a bean. Methods of this class locate any descriptor information that has been explicitly supplied by the
developer through BeanInfo classes.

The following figure represents a hierarchy of the FeatureDescriptor classes:

Example:

SimpleBean.java

package introspectionexample;

import java.io.Serializable;

public class SimpleBean implements Serializable{

private String Name = "SimpleBean";


private int size;

public int getSize() {


return size;
}

public void setSize(int size) {


this.size = size;
}

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 3 | 20


Chapter-05 JavaBeans

SimpleBean.java(continued)

public String getName() {


return Name;
}

public void setName(String Name) {


this.Name = Name;
}
}

IntrospectionExample.java

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;

public class IntrospectionExample {


public static void main(String[] args)throws
IntrospectionException {
//Get bean information via Introspection
BeanInfo info=Introspector.getBeanInfo(SimpleBean.class);

//Display properties of a bean


for(PropertyDescriptor pd:info.getPropertyDescriptors())
System.out.println("Field of SimpleBean=" +
pd.getName() );

for(MethodDescriptor md:info.getMethodDescriptors())
System.out.println("Methods of SimpleBean=" +
md.getName());
}
}

This example creates a non-visual bean and displays the following properties derived from the BeanInfo
object:
 class
 name
 size

Note that a class property was not defined in the SimpleBean class. This property was inherited from
the Object class. To get properties defined only in the SimpleBean class, use the following form of the
getBeanInfo method:

Introspector.getBeanInfo( SimpleBean.class, Object.class);

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 4 | 20


Chapter-05 JavaBeans
5.3: Bean Customization
Customization provides a means for modifying the appearance and behavior of a bean within an application
builder so it meets your specific needs.

The following links are useful for learning about property editors and customizers:
 PropertyEditor(in the API reference documentation) interface
 PropertyEditorSupport(in the API reference documentation) class
 PropertyEditorManager(in the API reference documentation) class
 Customizer(in the API reference documentation) interface
 BeanInfo(in the API reference documentation) interface

A bean's appearance and behavior can be customized at design time within beans-compliant builder tools.
There are two ways to customize a bean:

 By using a property editor: Each bean property has its own property editor. The NetBeans GUI
Builder usually displays a bean's property editors in the Properties window. The property editor that
is associated with a particular property type edits that property type.

 By using customizers. Customizers give you complete GUI control over bean customization.
Customizers are used where property editors are not practical or applicable. Unlike a property editor,
which is associated with a property, a customizer is associated with a bean.

 Property Editors:
 A property editor is a tool for customizing a particular property type.
 Property editors are activated in the Properties window.
 This window determines a property's type, searches for a relevant property editor, and displays the
property's current value in a relevant way.
 Property editors must implement the PropertyEditor interface, which provides methods to
specify how a property should be displayed in a property
sheet.
The following figure represents the Properties window
containing myBean1 properties:

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 5 | 20


Chapter-05 JavaBeans
You begin the process of editing these properties by clicking the property entry. Clicking most of these
entries will bring up separate panels.

Example: To set up the foreground or background use selection boxes with choices of colors, or press the
“.....” button to work with a standard ColorEditor window. Clicking on the toolTipText property opens a
StringEditor window.

How Property Editors are Associated with Properties:

Property editors are discovered and associated with a given property in the following ways:

 Explicit association by way of a BeanInfo object. The editor of the title's property is set with the
following line of code:
pd.setPropertyEditorClass(TitleEditor.class);

 Explicit registration by way of the

java.beans.PropertyEditorManager.registerEditor method.
This method takes two arguments: the bean class type, and the editor class to be associated with that
type.

 Name search. If a class has no explicitly associated property editor, then the
PropertyEditorManager searchs for that class's property editor in the following ways:

o Appending “Editor” to the fully qualified class name.


Example: for the my.package.ComplexNumber class, the property editor manager
would search for the my.package.ComplexNumberEditor class.

o Appending “Editor” to the class name and searching a class path.

 Customizers:
 Customizers gives you complete GUI control over bean customization.
 When you use a bean Customizer, you have complete control over how to configure or edit a bean.
 A Customizer is an application that specifically targets a bean's customization.
 Customizers are used where property editors are not practical or applicable.
 Unlike a property editor, which is associated with a property, a customizer is associated with a bean.
 It provides a higher level of customization when compared to property editors.

All Customizer must:


o Extend java.awt.Component or one of its subclasses.
o Implement the java.beans.Customizer interface. This means implementing methods
to register PropertyChangeListener objects, and firing property change events at
those listeners when a change to the target bean has occurred.
o Implement a default constructor.
o Associate the customizer with its target class via BeanInfo.getBeanDescriptor.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 6 | 20


Chapter-05 JavaBeans

5.4: 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 non-volatile 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 (in the API reference documentation) interface, or the
java.io.Externalizable (in the API reference documentation) 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.

5.5: Creating java bean:

If you develop applications using Java Beans, probably the most central activity will be creating new Beans.
Often you will be able to get by using built-in beans and changing their properties. You can build all sorts of
dialog boxes using standard JBuilder beans.

When you cannot get the needed features this way, it is coding time. You have two options for creating
beans starting from scratch and starting from an existing bean.
 Starting from scratch is quite a bit more work, since you cannot control any other class' code. It is by
far more desirable to start from existing bean, if at all possible. The whole idea of object-oriented
programming is reuse.
 JBuilder comes to your aid when creating new beans. With its built-in wizards, it takes most of the
cut-and-paste grunt work out of the process.

The steps that must be followed while creating a new bean are:

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.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 7 | 20


Chapter-05 JavaBeans
Example:

import java.awt.Color;
import java.beans.XMLDecoder;
import javax.swing.JLabel;
import java.io.Serializable;

public class SimpleBean extends JLabelmimplements Serializable


{
public SimpleBean() {
setText( "Hello world!" );
setOpaque( true );
setBackground( Color.RED );
setForeground( Color.YELLOW );
setVerticalAlignment( CENTER );
setHorizontalAlignment( CENTER );
}
}

Then include Bean Jar file & manifest file:


JAR file allows you to efficiently deploy a set of classes and their associated resources. JAR file makes it
much easier to deliver, install and download. It is compressed.
The JAR file will contain the manifest and the SimpleBean class file:
Syntax for creating jar file using manifest file is:
Syntax: C:\Beans >jar cfm MyBean.jar MyBean.mf MyBean.class

Load JAR File:

To Load Jar File Go to Beanbox/File/Loadjar. In the above steps we have to select our created jar file when
we click on ok, our bean (userdefined) MyBean appear in the ToolBox.
Use the NetBeans IDE GUI Builder to load the jar file as follows:
1. Start NetBeans.
2. From the File menu select "New Project" to create a new application for a bean. One can use "Open
Project" to add bean to an existing application.
3. Create a new application using the New Project Wizard.
4. Select a newly created project in the List of Projects, expand the Source Packages node and select the
Default Package element.

5. Click the right mouse button and select New|JFrameForm from the pop-up menu.
6. Select the newly created Form node in the Project Tree. A blank form opens in the GUI Builder view
of an Editor tab.
7. Open the Palette Manager for Swing/ AWT components by selecting Palette Manager in the Tools
menu.
By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 8 | 20
Chapter-05 JavaBeans
8. In the Palette Manager window select the beans components in the Palette tree and press the "Add
from JAR" button.
9. Specify a location for Simp1¥Bean JAR file and follow tlte Add from JAR Wizard instructions.
10. Select the Palette and Properties options from the Windows menu.
11. Expand the beans group in the Palette window. The SimpleBean object appears. Drag the
SimpleBean object to the GUI Builder panel.
The following figure represents the SimpleBean object loaded in the GUI Builder panel:

5.5 Adding controls:


You can add Java controls such as buttons to your beans - you just have to make sure you base your bean on
a class that's a container, such as the Panel class. ·
Here's an example, in which we add a button to a bean and have the bean display the number of times it has
been clicked. We start by creating this bean, which we will call "button", on the Panel class and adding it to
package. Here's how we create the panel, size it, and add a button to it:

button.java

package sunw.demo.button;
import Java. awt.*;
import Java. awt. event. *;
public class button extends Panel implements ActionListener {
{

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 9 | 20


Chapter-05 JavaBeans

button.java(continued)

int count;
Button button I;
public butto() {
count=0;
setSize(200, 100);
buttonl =new Button("Click me");
button I .addActionListener( this);
add(button 1 );
}
}

All that's left now is to make the button active by incrementing the click count when the button is clicked,
repainting the bean to display the click count, and creating the paint () method:

button.java(continued)

package sunw.demo.button;
import java.awt. *;
import java.awt.event. *;
public class button extends panel implements ActionListener {
int count;
Button button 1;
public button() {
count= 0;
setSize(200, 100);
button I =new Button("Click me");
button I .addActionListener(this);
add(button 1 );
}
public void actionPerformed(ActionEvent e) {
count++; repaint();
}
public void paint(Graphics g) {
Dimension dimension = getsize();
int h = dimension.height;
int w =dimension.width;
g.setColor(new Color(255, 0, 0));
g.fillRect(0, 0, w-1, h-1 );
g.setcolor( new Color(0, 0, 0));
g.drawstring("c 1 ick count = " + count, 50, 50);
}
}

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 10 | 20


Chapter-05 JavaBeans
5.6 Bean properties:
A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of bean
properties include color, label, font, font size, and display size.
The JavaBeans specification defines the following types of bean properties:
 Simple – A bean property with a single value whose changes are independent of changes in any other
property.
 Indexed – A bean property that supports a range of values instead of a single value.
 Bound – A bean property for which a change to the property results in a notification being sent to
some other bean.
 Constrained – A bean property for which a change to the property results in validation by another
bean. The other bean may reject the change if it is not appropriate.

Bean properties can also be classified as follows:

 Writable – A bean property that can be changed


o Standard
o Expert
o Preferred
 Read Only – A bean property that cannot be changed.
 Hidden – A bean property that can be changed. However, these properties are not disclosed with the
BeanInfo class

BeanBuilder uses this schema to group and represent properties in the Properties window.

Simple properties:

To add simple properties to a bean, add appropriate getXXX and setXXX methods (or isXXX and
setXXX methods for a boolean property).

The names of these methods follow specific rules called design patterns. These design pattern-based method
names allow builder tools such as the NetBeans GUI Builder, to provide the following features:

 Discover a bean's properties


 Determine the properties' read/write attributes
 Determine the properties' types
 Locate the appropriate property editor for each property type
 Display the properties
 Alter the properties (at design time)

Example: A builder tool, on introspecting your Bean, discovers two methods:


public Color getColor() { ... }
public void setColor(Color c) { ... }
From this the builder tool infers that a property named color exists, that it is readable and writable, and
that its type is Color. Further, the builder tool can attempt to locate a property editor for that type, and
display the property (usually in a property sheet) so it can be edited.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 11 | 20


Chapter-05 JavaBeans

Adding a Color Property to SimpleBean:

Make the following changes to SimpleBean.java to add a color property:

//Create and initialize a private instance variable.


private Color color= Color.green;
//Write a public getter method.
public Color getColor(){ return color;
//Write a public setter method.
public void setColor(Color newColor){
color= newColor; repaint();
}
//Override the paint() method inherited from Canvas.
public void paint( Graphics g) {
g.setColor(color);
g.fi11Rect(20, 5, 20, 30);
}

Compile the Bean, load it in the TooIBox, and create an instance in the BeanBox.

Indexed properties:

The above discussed properties have only one value. For each named property, we have a single associated
value. But this is not always the best way to represent properties; sometimes a property is better modelled as
having multiple values.

You can create properties that an indexed property is an array of properties or objects that supports a range
of values and enables the accessor to specify an element of a property to read or write

Indexed properties are specified by the following methods:

//Methods to access individual values


public T getPropertyName(int index)
public void setPropertyName(int index, T element)

and
//Methods to access the entire indexed property array
public T[] getPropertyName()
public void setPropertyName(T element[])

Where, T is the type.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 12 | 20


Chapter-05 JavaBeans
Here is an example for indexed properties, the bean class provides methods for getting and setting a
specific element of the array.

public int getTestGrades(int index) {


return mTestGrades[index];
}

public void setTestGrades(int index, int grade) {


mTestGrades[index] = grade;
}

The bean class also provides a method for getting and setting the entire array.

public int[] getTestGrades() {


return mTestGrades;
}

public void setTestGrades(int[] tg) {


mTestGrades = tg;
}

Design Pattern events:


A bean class can fire off any type of event, including custom events. As with properties, events are identified
by a specific pattern of method names.
Beans send event notifications to event listeners that have registered themselves with a bean. Beans use the
delegation event model. An event is generated by the bean and sent to other objects by using following
design patterns:

//Multicast an event to multiple listeners.


public void add<Event>Listener(<Event>Listener a)
public void remove<Event>Listener(<Event>Listener a)

These methods are used to add or remove a listener for the specified event. The listener type must be a
java.util.EventListener.

Example: To add support for event listener that implements the ActionListener interface then we
write:

//Multicast an event to multiple listeners.


public void addActionListener(ActionListener al);
public void removeActionListener(ActionListener al);

The ActionListener interface is used to receive actions like mouse clicks.

Beans can generate two kinds of events: they are


1. unicast
2. multicast.
By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 13 | 20
Chapter-05 JavaBeans

Unicast: Allows only one listener to register for events. If an attempt is made to register other listeners, the
Bean must throw a java.util.TooManyListenersException.

Events use the following design pattern:

public void add<EventListenerType>(<EventListenerType> theListener);


public void remove<EventListenerType>(<EventListenerType> theListener);

Where, the <EventListenerType> must implement the java.util.EventListener interface. By


default, events are assumed to be multicast, unless the add accessor is declared to throw a
java.util.TooManyListenersException.
Example: Here is a unicast event called Update:

public void addUpdate (Update theListener)


throws java.utilTooManyListenersException;
public void removeUpdate (Update theListener);
throws java.utilTooManyListenersException;

Multicast: Allows multiple listeners to register for events


Example: Here, is a multicast event called Click:

public void addClick (Click theListener);


public void removeClick (Click theListener);

Bound properties:
A bound property notifies listeners when its value changes. JavaBeans follow the Observer pattern to do this
notification. Properties notifying observers about their changes are referred to as bound properties, as most observers
bind a special behavior to property changes. This has two implications:

1. The bean class includes addPropertyChangeListener() methods and


removePropertyChangeListener() methods for managing the bean's listeners.
public void addPropertyChangeListener(PropertyChangeListener p){
changes.addPropertyChangeListener(p);
}
public void removePropertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener(p);
}

2. When a bound property is changed, the bean sends a PropertyChangeEvent to its registered
listeners.
public interface PropertyChangeListener extends EventListener {
public void propertyChange(PropertyChangeEvent e );
}
PropertyChangeEvent and PropertyChangeListener live in the java.beans package.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 14 | 20


Chapter-05 JavaBeans
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.

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);
}
}

Constrained properties:

A constrained property is a special kind of bound property. For a constrained property, the bean keeps track
of a set of veto listeners.

The veto listeners are separate from the property change listeners. Fortunately, the java.beans package
includes a VetoableChangeSupport class that greatly simplifies 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.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 15 | 20


Chapter-05 JavaBeans
Syntax:
public void setPropertyName(PropertyType pt)
throws PropertyVetoException
{
//Code
}
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.

Note:
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.

5.7 Bean Methods:

 A JavaBean provides methods for services it exposes.


 Methods are defined for use at run time when the application wishes to use the bean's services.
 JavaBean methods follow the same lexical and syntactical rules as those followed by Java
methods and have the same invocation semantics and mechanisms as those available to regular
Java methods.
 JavaBean methods are defined with the public modifier that makes them available to other
components in the application.
 Other method modifiers such as final and synchronised can be used with JavaBean methods.
 However, not all methods defined in a JavaBean are considered to be JavaBean methods. This
distinction is necessary to distinguish high-level services offered by the bean from low-level
implementation mechanisms such as Java declarations, without burdening the language with
unnecessary keywords and concepts.
 Any public method defined with a name that does not start with the reserved prefixes get, is, set,
add, and remove is considered to be a JavaBean method. The reserved keywords are used in
conjunction with JavaBean properties and events.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 16 | 20


Chapter-05 JavaBeans
5.8 Bean an Icon:
You may have noticed that some beans have icons in the BeanBox. You can add your own icons to your
beans - all you have to do is add a getIcon() method to the Beanlnfo class. Here's how to implement this
method and handle all possibilities -monochrome or color icons of either 16x 16 or 32x32 pixels:

public java.awt.lmage getlcon(int iconKind) {


if (iconKind == Beaninfo.ICON _MONO_ J 6x 16 ||
iconKind == Beanlnfo.ICON_ COLOR_I6x 16)
{
java.awt.lmage image = loadlmage("lconl6.gif');
return image;
}
if(iconKind == Beanlnfo.ICON_COLOR_32x32 ||
iconKind == Beanlnfo.ICON_ COLOR_32x32)
{
java.awt.Image image= loadlmage("lcon32.gif');
return image;
}
return null;
}

5.9 BeanInfo class:


A BeanInfo is a class that changes how your bean appears in a builder tool. A builder tool can query the
BeanInfo to find out which properties it should display first and which should be hidden.
The BeanInfo class for your bean should have the same name as the bean class, with BeanInfo
appended.
For example, the FaceBean class has a corresponding FaceBeanBeanInfo class that describes it.
Now we will see how to creating a Beanlnfo Class.
The ExplicitButtonBeaninfo demo class is uses to creating a BeanInfo class. Following are the
general steps to make a BeanInfo class:
Step 1: Name your Beanlnfo Class:
You must append the string "Beanlnfo" to the target class name. If the target class name is
ExplicitButton, then its associated Bean information class must be named
ExplicitButtonBeanlnfo.
Step 2: Subclass SimpleBeanlnfo:
This is a convenience class that implements Beanlnfo methods to return null, or an equivalent
no-op value.
public class ExplicitButtonBeanlnfo extends SimpleBeanlnfo {
Using SimpleBeanInfo saves you from implementing all the BeanInfo methods, you only
have to override those methods you need.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 17 | 20


Chapter-05 JavaBeans
Step 3: Override the Appropriate Methods to Return the Properties, Methods, or Events that you
want
Step 4: Optionally Associate an Icon with the Target Bean
Step 5: Specify the Target Bean class, and, if the Bean has a Customizer, Specify it also

5.9 Java Beans API


The JavaBeans functionality is provided by a set of classes and interfaces in the java.beans package.
Table 3.1 lists the interfaces in java.beans and provides a brief description of their functionality

Interface Description
AppletInitializer This interface is designed to work in collusion with java.beans.Beans.instantiate.
BeanInfo Bean Info A bean implementor who wishes to provide explicit information about
their bean may provide a BeanInfo class that implements this Beanlnfo interface
and provides explicit information about the methods, properties, events, etc., of
their bean.
Customizer A customizer class provides a complete custom GUI for customizing a target Java
Bean.
Design Mode This interface is intended to be implemented by, or delegated from, instances of
java.beans.beancontext. BeanContext, in order to propagate to its
nested hierarchy of java.beans.beancontext.BeanContextChild
instances, the current "designTime" property.
ExceptionListener An ExceptionListener is notified of internal exceptions.

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


property.
PropertyEditor A PropertyEditor class provides support for GUIs that want to allow users to edit
a property value of a given type.
VetoableChangeListener A VetoableChange event gets fired whenever a bean changes a "constrained"
property. Visibility Under some circumstances a bean may be run on servers
where a GUI is not available.

Table 3.2 lists the classes in java.beans

Class Description
BeanDescriptor A BeanDescriptor provides global information about a "bean", including its
Java class, its displayName, etc.
Beans This class provides some general purpose beans control methods.
DefaultPersistenceDelegate The DefaultPersistenceDelegate is a concrete implementation of the abstract
PersistenceDelegate class and is the delegate used by default for classes about
which no information is available.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 18 | 20


Chapter-05 JavaBeans

Class Description
Encoder An Encoder is a class which can be used to create files or streams that
encode the state of a collection of JavaBeans in terms of their public APIs.
EventHandler The EventHandler class provides support for dynamically generating event
listeners whose methods execute a simple statement involving an incoming
event object and a target object.

EventSetDescriptor An EventSetDescriptor describes a group of events that a given Java bean


fires.
Expression An Expression object represents a primitive expression in which a single
method is applied to a target and a set of arguments to return a result-as in
"a.get.Foo()".
FeatureDescriptor The FeatureDescriptor class is the common baseclass for
PropertyDescriptor, EventSetDescriptor, and MethodDescriptor, etc.
IndexedPropertyChangeEvent An "lndexedPropertyChange" event gets delivered whenever a component
that conforms to the JavaBeans specification (a "bean") changes a bound
indexed property.

IndexedPropertyDescriptor An IndexedPropertyDescriptor describes a property that acts like an array


and has an indexed read and/or indexed write method to access specific
elements of the array
Introspector The lntrospector class provides a standard way for tools to learn about the
properties, events, and methods supported by a target Java Bean.
MethodDescriptor A MethodDescriptor describes a particular method that a Java Bean
supports for external access from other components.

ParameterDescriptor The ParameterDescriptor class allows bean implementers to provide


additional information on each of their parameters, beyond the low-level
type information provided by the java.lang.reflect.Method class
PersistenceDelegate The PersistenceDelegate class takes the responsibility for expressing the
state of an instance; of a given class in terms of the methods in the class's
public API.
PropertyChangeEvent A "PropertyChange" event gets delivered whenever a bean changes a
"bound" or "constrained" property.
PropertyChangeListenerProxy A class which extends the EventListenerProxy specifically for adding a
named PropertyChangeListener.

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

Property Descriptor A PropertyDescriptor describes one property that a Java Bean exports via a
pair of accessor methods.
PropertyEditorManager The PropertyEditorManager can be used to locate a property editor for any
given type name.

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

SimpleBeanlnfo This is a support class to make.it easier for people to provide Beanlnfo
classes.
Statement A Statement object represents a primitive statement in which a single
method is applied to a target and a set of arguments - as in "a.setFoo(b )".

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 19 | 20


Chapter-05 JavaBeans

Class Description
VetoableChangeListenerProxy A class which extends the EventListenerProxy specifically for associating a
VetoableChangeListener with a "constrained" property.
VetoableChangeSupport This is a utility class that can be used by beans that support constrained
properties.
XMLDecoder The XMLDecoder class is used to read XML documents created using the
XMLEncoder and is used just like the ObjectlnputStream
XML Encoder The XMLEncoder class is a complementary alternative to the
ObjectOutputStream and can used to generate a textual representation of a
JavaBean in the same way that the ObjectOutputStream can be used to
create binary representation of Serializable objects.

By, Suma M G, AP, Dept. of MCA RNSIT, Bengaluru 20 | 20

You might also like