You are on page 1of 60

Java Beans

Introduction to JavaBeans
A first definition of what JavaBeans are:
A JavaBean is a reusable software
component that can be manipulated visually
in a builder tool.
Definition of a software component:
Software components are self-contained
software units developed according to the
motto.
Developed them once, run and reused
them everywhere. Or in other words,
reusability is the main concern behind the
component model.

Software components offer predefined


services other components or
applications can make use of.
JavaBeans is one of Suns component
models
JavaBeans offer their services by exposing
properties, events and methods.
The features a component exposes can
be manipulated visually in a builder tool.
JavaBean is defined as a reusable
platform-neutral software component.

Definition of a builder tool


Builder tools allow a developer to work
with JavaBeans in a convenient way.
By examining a JavaBeans by a process
known as Introspection
A builder tool maintains a list of all
JavaBeans available. It allows you to
compose the Bean into applets,
application,servlets and composite
components and customize its behavior
and appearance by modifying its
properties and connect other components
to the event of the Bean or vice versa.

Examples of "builder tools":


Bean Box (part of Sun's basic Beans
Development Kit (BDK) - available
free fromjava.sun.com)
Sun Java Workshop
IBM Visual Age for Java
Symantec Visual Cafe
Borland JBuilder

Objectives
Notion of component on top of Java.
Designed mostly for the construction of
graphical user interface
The goal of the Java Beans APIs is to
define a software component model for
Java.
components that can be composed
together into applications by end users.

Features
Unifying features of Java Bean component :
support for introspection
so that a builder tool can analyze how a bean
works
support for customization
so that when using a builder tool a user can
customize the appearance and behaviour of a bean
support for events
as a simple communication metaphor that can be
used to connect up beans
support for properties
both for customization and for programmatic use
support for persistence
so that a bean can be customized in builder tool
and that have its customized state saved away and
reloaded later

Characteristics
Its capability spans from simple
functions to complex functions.
It may be visible or invisible to a
user.
It may work autonomously on a user
computer or it may cooperate on
some task with other components.

Java Bean conventions


There are two primary conventions
that must be followed in creating Java
Bean classes:
each "property" of the Java Bean class is
implemented by defining two public
functions (a "get" function and a "set"
function)
the "operations" of the Java Bean class are
the other public functions defined in the
class

/* file Thermometer.java */
public class Thermometer {
/* these two functions define the
"currentTemperature" property */
public int getCurrentTemperature() { return
temp; }
public void setCurrentTemperature(int aTemp)
{ temp = aTemp; }
private int temp;
public void
temperatureChanged(TempChangedEvent ev)
{ ... } ... other implementation details ... }

Invoking methods
In a bean component, various
methods can be invoked for
executing code.
In order to connect two components,
a mapping must be done between
the event generated by the quote
bean and appropriate
method
of
the
Graph
Quote
Bean
graphBean
bean.

Bean Developer Kit(BDK)


BDK is a development tool through
which java beans can be created,
configured, executed or interconnected.
Installing the BDK:
Download the BDK from the site,
http://www.ecst.csuchico.edu/~amk/foo/a
dvjava/notes/beans/BDK/
The file is bdk1_1.zip

Installation(cont)
C:\beans
Bean box
Run.bat

Starting the BeanBox


When you start the BeanBox, you'll see
three windows:
ToolBox window
BeanBox window
Properties window

The ToolBox windowdisplays the


JavaBeans that are currently installed in
the BeanBox
The BeanBox windowitself appears
initially as an empty window.
the Properties window, displays the
current properties for the selected Bean
Method tracer, used to keep an eye
on the activities of bean,mainly used
for debugging purpose.

Create and Configure an


Instance of the Molecule
Bean
Follow these steps

1.Position the cursor on the ToolBox entry labeled


Molecule and click the left mouse button.
2.Move the cursor to the BeanBox display area
and click the left mouse button.
3.You can reposition the Molecule Bean by
positioning the cursor over one of the
hatched borders and dragging the Bean.
4.You can change the molecule that is displayed
by changing the selection in the Properties
window

Create and Configure an


Instance of the OurButton
Bean
1. Position the cursor on the ToolBox entry
labeled OurButton and click the left
mouse button.
2. Move the cursor to the BeanBox display area
and click the left mouse button.
3. You may reposition the OurButton Bean by
positioning the cursor over one of the
hatched borders and dragging the Bean.
4. Go to the Properties window and change the
label of the Bean to Rotate X.The button
appearance changes immediately when this
property is changed.

5. Go to the menu bar of the BeanBox and


select Edit | Events | action |
actionPerformed.
6. Move the cursor so that it is inside the
Molecule Bean display area, and click
the left mouse button. You should see the
Event Target Dialog dialog box.
7. The dialog box allows you to choose a
method that should be invoked when this
button is clicked. Select the entry labeled
rotateOnX and click the OK

Instrospection
builder tools typically provide a property
sheet where one can conveniently set the
properties of a JavaBean component.
In order to provide this service a builder tool
needs to examine the component for its
features (=properties, events and methods).
This process is referred to as introspection.
To obtain information about a specific
JavaBean one can use the static
getBeanInfo() method of the Introspector
class.

This method returns an instance of


the BeanInfo class, which describes
all features a JavaBean exposes.
use of this method is shown in the
following code fragment:
FontSelector fs = new FontSelector
();
BeanInfo bi = Introspector .
getBeanInfo (fs. getClass ());

The following example represents code to perform


introspection

import
import
import
import

public class BeanDemo


{
private final String name = "BeanDemo";
private int size;

java.beans.BeanInfo;
java.beans.Introspector;
java.beans.IntrospectionException;
java.beans.PropertyDescriptor;

public String getName()


{
return this.name;
}

public int getSize()


{
return this.size;
}

public void setSize( int size )


{
this.size = size;
}

public static void main( String[] args )


throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( BeanDemo.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}

The above example creates a nonvisual bean displays the following


properties derived from the BeanInfo
object.
out out:
class
name
size

BeanInfo Interface
A bean implementor who wishes to
provide explicit information about their
bean may provide a BeanInfo class that
implements this BeanInfo interface and
provides explicit information about the
methods, properties, events, etc, of their
bean.

Method Detail
getBeanDescriptor
public BeanDescriptor
getBeanDescriptor()
Gets the beansBeanDescriptor.
Returns:A BeanDescriptor providing
overall information about the bean

getEventSetDescriptors
public EventSetDescriptor[]
getEventSetDescriptors()

Gets the beansEventSetDescriptors.


Returns:An array of
EventSetDescriptors describing the
kinds of events fired by this bean

getDefaultEventIndex
public int getDefaultEventIndex()
A bean may have a "default" event that
is the event that will mostly commonly
be used by humans when using the bean.
Returns:Index of default event in the
EventSetDescriptor array returned by
getEventSetDescriptors.Returns -1 if
there is no default event.

getPropertyDescriptors
public PropertyDescriptor[]
getPropertyDescriptors()

Gets the beansPropertyDescriptors.


Returns:An array of
PropertyDescriptors describing the
editable properties supported by this
bean.

getDefaultPropertyIndex
public int getDefaultPropertyIndex()
A bean may have a "default" property that
is the property that will mostly commonly
be initially chosen for update by human's
who are customizing the bean.
Returns:Index of default property in the
PropertyDescriptor array returned by
getPropertyDescriptors.Returns -1 if there is
no default property.

getMethodDescriptors
public MethodDescriptor[]
getMethodDescriptors()

Gets the beansMethodDescriptors.


Returns:An array of
MethodDescriptors describing the
externally visible methods supported
by this bean

getAdditionalBeanInfo
public BeanInfo[]
getAdditionalBeanInfo()
that provide additional information on
the current bean
getIcon
public Image getIcon(inticonKind)
This method returns an image object
that can be used to represent the
bean in toolboxes

Properties
There exist four different kinds of
properties a JavaBean can expose:
1.Simple
2.Indexed
3.Bound
4.Constrained
All types of property have in common
that they are characterized by a pair
of set/get methods.

Simple Properties
As the name suggests, simple
properties are the simplest of the
four.
we would like to have a default font
size, which will be used as initial font
size at runtime.

Design patterns, where N is the


name of the property and T is its
type.
public T getN( );
public void setN(T arg);

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

Indexed Properties
If a simple property can hold an array
of value they are no longer called
simple but instead indexed properties
An indexed property may expose
set/get methods to read/write one
element in the array and/or so-called
array getter/setter which read/write
the entire array.

design patterns, where N is the name


of the property and T is its type:
public
public
public
public

T getN(int index);
void setN(int index, T value);
T[ ] getN( );
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 = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);
}
}

JAR Files
Tools such as the BDK expect Beans to
be packaged within JAR files. A JAR file
allows you to efficiently deploy a set of
classes and their associated resources.
Manifest Files
A developer must provide a manifest
file to indicate which of the components
in a JAR
file are Java Beans.

Name: sunw/demo/slides/Slides.class
Java-Bean: True
A manifest file may reference
several .class files. If a .class file is
a Java Bean, its entry must be
immediately followed by the line
Java-Bean: True.
The JAR Utility
A utility is used to generate a JAR file.
Its syntax is shown here:
jar options files

Creating a JAR File


The following command creates a JAR
file named Xyz.jar
jar cf Xyz.jar *.class *.gif
If a manifest file such as Yxz.mf is
available, it can be used with the
following command:
jar cfm Xyz.jar Yxz.mf *.class *.gif

Developing a Simple Bean


Using the BDK
Our new component is called the
Colors Bean. It appears as either
a rectangle or ellipse that is filled
with a color.
The button is labeled Change. Each
time it is
pressed, the color changes.

Create a New Bean


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.

1.Create a Directory for the New Bean


create
c:\bdk\demo\sunw\demo\colors.
Then change to that directory.
2. Create the Source File for the New
Bean
It is located in the file Colors.java.

// A simple Bean.
package sunw.demo.colors;
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);
}
}
}

3.Compile the Source Code for the New


Bean
javac Colors.java.
4. Create a Manifest File
Name: sunw/demo/colors/Colors.class
Java-Bean: True
5. Generate a JAR File
jar cfm ..\jars\colors.jar colors.mft
sunw\demo\colors\*.class

6.Start the BDK


Change to the directory
c:\bdk\beanbox and type run
This causes the BDK to start
The ToolBox window should include
an entry labeled Colors for your
new Bean.

Bound Properties
A Bean that has a bound property generates
an event when the property is changed.
The event is of type
PropertyChangeEvent and is sent to
objects that previously registered an
interest in receiving such notifications.
The TickTock Bean is supplied with the
BDK. It generates a property change
event
every N seconds.

Implementing Bound Property


Support Within a Bean:
To implement a bound property, take
the following steps:
1.Import thejava.beanspackage. This gives you
access to thePropertyChangeSupportclass.
2.Instantiate a PropertyChangeSupport
object: private PropertyChangeSupport changes
= new PropertyChangeSupport(this);
This object maintains the property change
listener list and fires property change events.
3.Implement methods to maintain the
property change listener list.

public void
addPropertyChangeListener(PropertyChangeListener l)
{ changes.addPropertyChangeListener(l); }
public void
removePropertyChangeListener(PropertyChangeListener
l)
{ changes.removePropertyChangeListener(l); }
4.Modify a property's setter method to fire a
property change event when the property is
changed.
public void setLabel(String newLabel)
{
String oldLabel = label;
label = newLabel;
sizeToFit();
changes.firePropertyChange("label", oldLabel, newLabel);
}

Constrained Properties
A Bean that has a constrained property
generates an event when an attempt is
made to change its value. The event is of
type PropertyChangeEvent. It is sent
to objects that previously registered an
interest in receiving such notifications.
Those other objects have the ability to
veto the proposed change. This capability
allows a Bean to operate differently
according to its run-time environment.

Persistence
Persistence is the ability to save a Bean to
nonvolatile storage and retrieve it at a later
time.
Inorder to do this we take the help of BDK.
Saving the beans in the BDK :choose
file and then the save options.
Restoring the beans in the BDK:choose
file and then load options.

The Java Beans API


The Java Beans functionality is
provided by a set of classes and
interfaces in the
java.beans package.

Interface

Description

AppletInitializer

Methods in this interface are used


to initialize Beans that are also
applets.

BeanInfo

This interface allows a designer to


specify
information about the properties,
events, and methods of a Bean.

Customizer

This interface allows a designer to


provide a graphical user interface
through which a Bean may be
configured.

ExceptionListener

A method in this interface is


invoked when an exception has
occurred

PropertyChangeListener

A method in this interface is


invoked when a bound property is
changed.

PropertyEditor

Objects that implement this


interface allow designers to
change and display property
values

Interface

Description

VetoableChangeListener

A method in this interface is


invoked when a constrained
property is changed.

Visibility

Methods in this interface allow a


Bean to execute in environments
where a graphical user interface
is not available.

Class

Description

Encoder

Encodes the state of a set of


Beans. Can be used to write this
information to a stream

EventHandler

Supports dynamic event listener


creation

EventSetDescriptor

Instances of this class describe an


event that can be generated by a
Bean

FeatureDescriptor

This is the superclass of the


PropertyDescriptor,
EventSetDescriptor, and
MethodDescriptor
classes.

IndexedPropertyDescriptor

Instances of this class describe an


indexed
property of a Bean.

SimpleBeanInfo

This class provides functionality


that can be used when writing
BeanInfo classes

Class

description

IntrospectionException

An exception of this type is


generated if a
problem occurs when analyzing a
Bean.

Introspector

This class analyzes a Bean and


constructs a BeanInfo object
that describes the component

MethodDescriptor

Instances of this class describe a


method of a Bean.

ParameterDescriptor

Instances of this class describe a


method
parameter.

PropertyChangeEvent

This event is generated when


bound or constrained
properties are changed

PropertyDescriptor

Instances of this class describe a


property of a Bean.

PropertyEditorManager

This class locates a


PropertyEditor object for
agiven type.

You might also like