Sie sind auf Seite 1von 11

Nawaraj Paudel

Page 1

Chapter 4

JavaBeans
Introduction
JavaBeans are reusable software components for Java that can be manipulated visually in
a builder tool. JavaBeans components are known as beans. Particularly, they are classes
written in the Java programming language conforming to a particular convention. Using
visual application builder tools, software components can be composed into applets,
applications, servlets, and composite components.
Beans are dynamic in that they can be changed or customized. Through the design
mode of a builder tool you can use the Properties window of the bean to customize the
bean and then save (persist) your beans using visual manipulation. You can select a bean
from the toolbox, drop it into a form, modify its appearance and behavior, define its
interaction with other beans, and combine it and other beans into applet, application,
servlet, or a new bean.

Reusable Software Components


Reusable software components apply the concept of reusable and interchangeable parts to
the field of software construction. Reusable software components can be simple, such as
buttons, text fields, list boxes, scrollbars, and dialogs. Reusable components add
standardized interfaces and object introspection mechanisms to widgets, allowing builder
tools to query components about their properties and behavior. Keep in mind, too, that
software component need not be visible in a running program; they only need to be
visible when the application is constructed. A programmer can move, query, or visually
hook together components while operating a builder tool. Often, such components do
their work while the program is running, though they are invisible to the user.
You can purchase custom JavaBean components from third party vendors. You can
also purchase builder tools or application construction programs that support JavaBeans.
Application construction tools let you build Java applications using the mouse as your
primary input mechanism. You select components (from pallets, panels, or menus) and
drop them into a form, or client window. You can change the behavior and look of these
components by editing their properties, and you can link the actions of one component to
another via events and event handlers.
Components can be nested and arbitrarily complex. For example, a calculator built
from components becomes, itself, a component to another application. Custom-built
components are easily added to builder tool palettes.

What Distinguishes JavaBeans from Java Classes?


Any Java class that adheres to certain conventions regarding property and event interface
definitions can be a JavaBean. Beans are Java classes that can be manipulated in a visual
builder tool and composed into programs.
Introspection, the process by which a builder tool analyzes how a Bean works,
differentiates Beans from typical Java classes. Because Beans are coded with predefined

Advanced Programming Techniques

Nawaraj Paudel

Page 2

patterns for their method signatures and class definitions, tools that recognize these
patterns can "look inside" a Bean and determine its properties and behavior.
Introspection allows a Bean's state to be manipulated at design time that is, at the
time it is being assembled as a part within a larger program. For this to work, method
signatures within Beans must follow a certain pattern so that introspection tools recognize
how Beans can be manipulated, both at design time and at run time.
In effect, Beans publish their attributes and behaviors through special method
signature patterns that are recognized by beans-aware application construction tools.
However, these construction tools are not required to build or test your beans. The pattern
signatures are easily recognized by human readers, as well as builder tools. One of the
first things you'll learn when building beans is how to recognize and construct methods
that adhere to these patterns.

Basic Bean Concepts


A Java Bean is a reusable software component that can be visually manipulated in builder
tools. JavaBeans, regardless of their functionality, are defined by the following features.
Introspection: Beans support introspection, which allows a builder tool to
analyze how Beans work. They adhere to specific rules called design patterns for
naming Bean features. Each Bean has a related Bean information class, which
provides property, method, and event information about the Bean itself. Each
Bean information class implements a BeanInfo interface, which explicitly lists
the Bean features that are to be exposed to application builder tools.
Properties: Properties control a Bean's appearance and behavior. Builder tools
introspect on a Bean to discover its properties and to expose them for
manipulation. As a result, you can change a Bean's property at design time.
Customization: The exposed properties of a Bean can be customized at design
time. Customization allows a user to alter the appearance and behavior of a Bean.
Beans support customization by using property editors or by using special,
sophisticated Bean customizers.
Events: Beans use events to communicate with other Beans. Beans may fire
events, which mean the Bean sends an event to another Bean. When a Bean fires
an event it is considered a source Bean. A Bean may receive an event, in which
case it is considered a listener Bean. A listener Bean registers its interest in the
event with the source Bean. Builder tools use introspection to determine those
events that a Bean sends and those events that it receives.
Persistence: Beans use Java object serialization, implementing the
java.io.Serializable interface, to save and restore state that may have
changed as a result of customization. State is saved, for example, when you
customize a Bean in an application builder, so that the changed properties can be
restored at a later time.
Methods: All JavaBean methods are identical to methods of other Java classes.
Bean methods can be called by other Beans or via scripting languages. A
JavaBean public method is exported by default.

Advanced Programming Techniques

Nawaraj Paudel

Page 3

While Beans are intended to be used primarily with builder tools, they need not be. Beans
can be manually manipulated by text tools through programmatic interfaces.

Bean Development Kit (BDK) and Bean Box


BDK is delivered separately from the JDK. You can download it from the JavaBeans web
site and use it. The BeanBox is a simple tool you can use to test your Beans, and to learn
how to visually manipulate their properties and events. The BeanBox is not a builder tool.
You'll use the BeanBox to learn about Beans. You can create a JavaBean and then use the
BeanBox to test that it runs properly. If a JavaBean runs properly in the BeanBox, you
can be sure that it works properly with other commercial builder tools.

Starting the BeanBox


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

The ToolBox window displays the JavaBeans that are currently installed in the BeanBox,
such as the Beans they come with the BeanBox demo. When the BeanBox starts, it
automatically loads its ToolBox with the Beans in the JAR files contained in the bean/jars
directory. You can add additional Beans, such as your own Beans, to the ToolBox.
The BeanBox window itself appears initially as an empty window. You use this
empty window, sometimes referred to as a "form" by other builder tools, for building
applications.
The Properties window displays the current properties for the selected Bean. If no
Bean is selected, such as when you first start the BeanBox or if you click in the BeanBox
window's background, then the Properties window displays the BeanBox properties. You
can use the Properties window or sheet to edit a Bean's properties.

Advanced Programming Techniques

Nawaraj Paudel

Page 4

Using the BDK BeanBox


The easiest way to understand how the BeanBox works is to use it. The BeanBox enables
you to construct simple Beans applications without writing any Java code. As a first
example, you can build a simple "Juggling Duke" application in which Duke will start or
stop juggling depending on which of two buttons you push. In this lesson, you'll learn
how to:
Drop Beans from the ToolBox into the BeanBox and change their properties using
the Properties sheet and associated property editors.
Have one Bean fire an event and another Bean react to the fired event.

Creating your Bean


We'll start by dropping the Juggler Bean from the ToolBox into an empty BeanBox.
1. Click on Juggler Bean to select from the list of Beans in the Toolbox window.
Notice that the cursor changes to a crosshair.
2. Place the cursor anywhere in the BeanBox, then click the mouse. This inserts a
Juggler Bean into the BeanBox window. The highlighted box surrounding the
Juggler indicates the Juggler is the currently selected bean.
Next we'll look at adding a start button to control the Juggler. This button Bean is an
instance of the OurButton Bean class.
3. Click the OurButton Bean name in the ToolBox, then place an instance of the
button in the BeanBox. Select the button in the BeanBox so that the button's
properties display in the Property sheet.
4. Edit the label field in the button's Property sheet so that the button's label reads
"start."
Notice that the text for the button in the BeanBox changes from "press" to "start" after
you type "start" into the label field of the property sheet editor.
5. Use the BeanBox Edit menu to select an action event to be fired by the start
button. Before choosing the event action, be sure that you have selected the start
button.
Notice that once you select the actionPerformed menu item, BeanBox enters a state
where a line emanates from the start button and follows the mouse as you move it around
the window. This indicates that the button is the selected source for the action event, and
that your next mouse press should be over the target Bean which defines appropriate
event-handler methods, in this case the Juggler Bean.
6. Drag the line from the start button and release it over the Juggler Bean. A dialog
appears listing applicable event handlers defined by the Juggler Bean.
7. Select the startJuggling method as the target for the event, then press OK.
Now, when you press the start button Duke should start tossing beans around in a
circle over his head like a professional juggler.
You can control Duke's juggling speed by manually setting the property value labeled
animationRate in the Juggler's property sheet editor. For the appropriate property sheet
editor to appear, the Juggler must be the currently selected Bean within the BeanBox
frame.

Completing your Program

Advanced Programming Techniques

Nawaraj Paudel

Page 5

To complete the example program, add a stop button. Repeat the steps you took when
you added the start button and connected it to the appropriate Juggler action.
1. Select OurButton from the list of available Beans in the Toolbox menu, and then
drop it below the start button in the BeanBox.
When the new button is the currently selected Bean, the appropriate property editor
appears.
2. Edit the label field of the property sheet to read "stop."
3. Hook up the action event from the stop button to the Juggler's stopJuggling eventhandler method. Make sure the stop button is the currently selected bean.
4. Select the actionPerformed event from the Edit/Events menu.
5. Drag the event line from the stop button source to the Juggler Bean target. Press
and release the mouse button with the connection line over the Juggler.
6. The dialog of applicable event-handler methods defined for the Juggler Bean
displays; select the stopJuggling event and click OK.
You should now be able to start and stop the juggler by pressing the appropriate button.

Bean Writing Process


We use a number of different steps to write and test JavaBeans using Bean Development
Kit. These steps are:
1. Create a directory for the new Bean
2. Create the java source file(s)
3. Compile the source file(s)
4. Create manifest file.
5. Generate a JAR file.
6. Start the BDK.
7. Load the jar file.
8. Test the bean.
Create a directory for the new Bean
For example, c:\bdk\demo\simplebean
Create the java source file(s)
For example,
import java.awt.*;
import java.io.*;
public class SimpleBean extends Canvas implements
Serializable {
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}
}
Compile the source file(s)
javac SimpleBean.java
Create manifest file

Advanced Programming Techniques

Nawaraj Paudel

Page 6

User must create the manifest file to provide which components in the JAR file are java
beans. You can put any number of files in the manifest file entry but if you have class
files acting as java beans then each entry of the file must be immediately followed by the
line Java-Bean: True
For example,
Name: SimpleBean.class
Java-Bean: True
Name the file as SimpleBean.mft (or .tmp or of your choice)
Here if you have other resources you can append them using Name: resource path. While
including class name if you have created package write full path including package. The
above file indicates that there is only one class file in JAR file.
Generate a JAR file
jar cfm SimpleBean.jar SimpleBean.mft SimpleBean.class
Other three steps are as done previously.

Introspection
The introspection services provided by the JavaBeans API are divided into two parts:
low-level services and high-level services. The low-level API services are typically used
by application builder tools, which make heavy use of bean internals to provide advanced
development features. This level of access isn't appropriate for application developers,
however, because it exposes bean internals that aren't meant to be accessible at the
application level. For developers, the high-level API services are more appropriate. The
high-level services provide access to a limited portion of a bean's internals, which
typically consist of a bean's public properties, methods, and events. The high-level
introspection services rely heavily on the low-level services; the primary difference
between the two is that the high-level services limit access to bean internals.
There are two approaches to introspect. The automatic approach to introspection
provides bean information automatically. For those cases in which bean developers want
to get up close and personal with bean information, there is an explicit approach.
The first approach of JavaBeans automatically assessing information about a bean
uses the reflection facilities in the core Java API. The reflection facilities are responsible
for analyzing the low-level structure of a bean and returning information. The
introspection facilities in the JavaBeans API take this information and apply design
patterns to it to determine the specifics about the public properties, methods, and events
supported by a bean.
The explicit approach to defining bean information requires a little more work on the
part of bean developers. The JavaBeans API provides support classes that are used by
developers to explicitly define the public information for a bean. Keep in mind that this
approach is purely optional and can even be used in combination with the automatic
approach. In other words, developers are free to explicitly provide some bean information
and allow the introspection facilities to automatically determine the rest. It's important to
note that automatic introspection is the default approach taken by JavaBeans, and is
superseded only if explicit information is available. This ability to leverage both
introspection approaches provides lots of flexibility for bean developers.

Advanced Programming Techniques

Nawaraj Paudel

Page 7

Design Patterns
Bean developers are not required to add any additional support for introspection in their
code. They only have to structure the code for the bean itself because JavaBeans relies on
the naming and type signatures of the methods defined in the code for a bean to
determine what properties, methods, and events the bean supports for public use. In other
words, the conventions used in the code for a bean are also used as a means to introspect
the bean.
The automatic approach to JavaBeans introspection relies heavily on the naming
conventions and type signatures of a bean's methods, including methods for registering
event listeners. The approach relies on design patterns, which are standardized naming
conventions and type signatures that are used to define bean methods based on their
function.
There are a variety of different design patterns for specifying everything from simple
properties to event sources. All of these design patterns rely on some type of consistent
naming convention for methods and their related arguments and types. Keep in mind that
this approach to introspection is not only convenient from the perspective of JavaBeans,
but it also has the intended side effect of encouraging bean developers to use a consistent
set of naming conventions. Here are the three major types of design patterns, each of
which are discussed.
Property design patterns
Event design patterns
Method design patterns

Property Design Patterns


Properties are private values accessed through accessor methods (getter and setter
methods). Property getter and setter method names follow specific rules, called design
patterns. These methods are used to identify the publicly accessible properties of a bean.
It turns out that accessor methods are the means by which the JavaBeans automatic
introspection facilities determine which properties a bean exposes. Basically, any time the
JavaBeans introspector encounters a public getter or setter method, it assumes the
property in question is a public property and exposes it to the outside world.
Properties need not always have pairs of accessor methods. For example, if a property
has only a getter method, JavaBeans assumes it is a read-only property. Likewise, if a
property has only a setter method, JavaBeans assumes it is a write-only property. If both
methods are defined it is a read-write property. As you can see, design patterns are
amazingly simple, but quite effective. The design patterns for properties vary a little
based on the type of property.

1. Simple Property
Simple properties consist of all single-valued properties, which include all built-in
Java data types as well as classes and interfaces. For example, int, long, float,
Color, Font, and boolean are all considered simple properties. The design
patterns for simple property accessor (getters and setters) methods follow:
public <PropertyType> get<PropertyName>()

Advanced Programming Techniques

Nawaraj Paudel

Page 8

public void set<PropertyName>(<PropertyType> x)


So, for a property called color that is of type Color, the following accessor
methods would safely conform to the introspection design patterns:
public Color getColor()
public void setColor(Color c)
When the JavaBeans automatic introspector encounters these method definitions,
it determines both the color public property, as well as the getColor() and
setColor() accessor methods for accessing the property. And this takes place
without you having to do anything more than conform to the simple property
design patterns when you design your methods. For example,
import java.awt.*;
import java.io.*;
public class SimpleBean extends Canvas
Serializable {
private Color color = Color.green;
public Color getColor(){
return color;
}
public void setColor(Color newColor){
color = newColor;
repaint();
}
public void paint(Graphics g) {
g.setColor(color);
g.fillRect(20, 5, 20, 30);
}
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}
}

implements

2. Boolean Property
Boolean Properties are technically simple properties of boolean type. They
have an optional design pattern for the getter method that can be used to make it
more clear that a property is of boolean type. This design pattern follows:
public boolean is<PropertyName>() //preferred one
public boolean get<PropertyName>()
The only difference between this design pattern and the one for simple properties
is that it uses the word is instead of get in the name. It is fairly common for
Java developers to access boolean properties with an is method, which is why
JavaBeans supports the use of this special case design pattern. The following is an

Advanced Programming Techniques

Nawaraj Paudel

Page 9

example of a pair of accessor methods for a boolean property named


amphibious that conforms to the boolean design pattern:
public boolean isAmphibious()
public void setAmphibious(boolean a)
You might be wondering what happens in the event that both a get method and
an is method are defined for a property. Not to worry, JavaBeans handles this by
always using the is method if it is available, and the get method if not.

3. Indexed Property
An indexed property is an array of simple properties. Because indexed properties
require slightly different accessor methods, it only makes sense that their design
patterns differ a little from other properties. Here are the design patterns for
indexed properties:
//Methods to access individual values
public <PropertyType> get<PropertyName>(int index);
public void set<PropertyName>(int index, <PropertyType>
value);
//Methods to access the entire indexed property array
public <PropertyType>[] get<PropertyName>();
public void set<PropertyName>(<PropertyType>[] value);
The first pair of design patterns defines accessor methods for getting and setting
individual elements in an indexed property. The second pair of patterns defines
accessor methods for getting and setting the entire property array as a whole. For
example,
public
public
public
public

Color getPalette(int i);


void setPalette(int i, Color c);
Color[] getPalette();
void setPalette(Color[] c);

In this example, the indexed property is called palette and is an array of


Color objects. The first pair of accessor methods enable you to get and set
individual colors in the palette, and the second pair enables you to get and set the
whole palette of colors.

Advanced Programming Techniques

Nawaraj Paudel

Page 10

Event Design Patterns


When a bean's internal state changes, it often is necessary to notify an outside party of the
change. To accomplish this, beans are capable of broadcasting event notifications that
inform interested parties of some change in a bean. Events themselves can represent
many different types of notifications, but some of the most popular ones are mouse clicks
and drags. For example, when the user drags the mouse over a bean, you might want the
bean to notify its parent so the appearance of the cursor can be changed. This notification
is handled by the bean sending its parent an event. Beans send notifications to event
listeners that have registered themselves with a bean as wanting to receive event
notifications. Because listeners must register themselves with a bean, it is important that
beans provide appropriate methods to facilitate the registration process. The event
registration methods come in pairs, with one method enabling listeners to be added and
the other enabling beans to be removed. Because this method pair is sufficient for
defining an event registration between a bean and an interested party, it's probably not
going to come as a surprise to you that the JavaBeans introspector uses these methods to
assess the events that a bean is capable of sending.
Event registration methods must conform to the following design patterns for the
automatic introspection services to work properly:
public void add<EventListenerType>(<EventListenerType> x);
public void remove<EventListenerType>(<EventListenerType> x);

In these design patterns, <EventListenerType> refers to the object type of the event
listener being registered with the bean. JavaBeans requires that this
object implement the EventListener interface and have its name end with
Listener. Therefore, if you want to add support for an event listener implementing the
ActionListener interface, you would do so like this:
public void addActionListener(ActionListener al);
public void removeActionListener(ActionListener al);

The ActionListener interface is used to receive action events such as mouse clicks. In
this example, action listeners can easily be registered to receive actions by calling the
addActionListener() method, or removed as a listener by calling the
removeActionListener() method.
The event registration design patterns discussed thus far are designed for beans that
support multicast events, meaning that there can be multiple registered event listeners.
JavaBeans also supports the use of unicast event sources, which are beans that enable
only one listener at a time to receive event notifications. In other words, unicast beans
enable only one event listener to be registered at a particular time. If an attempt is made
to register more than one listener with a unicast bean, the add<EventListenerType>()
method is thrown a TooManyListenersException exception. The design pattern for this
method follows:
public
void
add<EventListenerType>(<EventListenerType>
TooManyListeners;

Here is the same action listener example designed for a unicast event source:

Advanced Programming Techniques

x)throws

Nawaraj Paudel
public

void

Page 11
addActionListener(ActionListener

al)

throws

TooManyListeners;
public void removeActionListener(ActionListener al);

Method Design Patterns


The last area to cover in regard to design patterns is related to public methods that aren't
accessor methods. These methods are completely user-defined in that they have no preestablished purpose such as getting or setting a property. Because the naming and type
signature for non-accessor public methods is totally up to the bean developer, there aren't
any specific design patterns governing them. JavaBeans assumes all public methods are
to be publicly exported for outside use. The only difference between these public
methods and public accessor methods is that accessor methods notify the JavaBeans
introspector of a bean property.

Bound Properties
Sometimes when a Bean property changes, another object may want 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. A Bean containing a bound property must maintain a
list of property change listeners, and alert those listeners when the bound property
changes. The convenience class PropertyChangeSupport implements methods that add
and remove PropertyChangeListener objects from a list, and fires
PropertyChangeEvent objects at those listeners when the bound property changes. Your
Beans can inherit from this class, or use it as an inner class. An object that wants to listen
for property changes must be able to add and remove itself from the listener list on the
Bean containing the bound property, and respond to the event notification method that
signals a property change. By implementing the PropertyChangeListener interface the
listener can be added to the list maintained by the bound property Bean, and because it
implements the PropertyChangeListener.propertyChange method, the listener can
respond to property change notifications.
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 via the propertyChange method.

Advanced Programming Techniques

Das könnte Ihnen auch gefallen