Professional Documents
Culture Documents
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).
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:
Persistence
Customizers
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.
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.
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.
Example:
SimpleBean.java
package introspectionexample;
import java.io.Serializable;
SimpleBean.java(continued)
IntrospectionExample.java
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
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:
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:
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.
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);
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:
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.
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.
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:
import java.awt.Color;
import java.beans.XMLDecoder;
import javax.swing.JLabel;
import java.io.Serializable;
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:
button.java
package sunw.demo.button;
import Java. awt.*;
import Java. awt. event. *;
public class button extends Panel implements ActionListener {
{
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);
}
}
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:
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
and
//Methods to access the entire indexed property array
public T[] getPropertyName()
public void setPropertyName(T element[])
The bean class also provides a method for getting and setting the entire array.
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:
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.
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:
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.
import java.beans.*;
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.
Catching exceptions.
Reverting to the old value for the property.
Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report
the reversion.
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.
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.
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.
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.
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.
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 )".
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.