Notes On JavaBeans
Notes On JavaBeans
Properties
Simple Properties
Bound Properties
Constrained Properties
Indexed Properties
Manipulating Events
Bean Persistence
Introspection
Bean Customization
A set of APIs describes a component model for a particular language. The JavaBeans API
specificationdescribes the core detailed elaboration for the JavaBeans component
architecture.
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 an applet, application, or a new
bean.
• Builder tools discover a bean's features (that is, its properties, methods, and
events) by a process known as introspection. Beans support introspection in two
ways:
o By adhering to specific rules, known as design patterns, when naming
bean features. The Introspector class examines beans for these design
patterns to discover bean features. The Introspector class relies on the
core reflection API. The trail The Reflection API is an excellent place to
learn about reflection.
o By explicitly providing property, method, and event information with a
related bean information class. A bean information class implements the
BeanInfo interface. A BeanInfo class explicitly lists those bean features
that are to be exposed to application builder tools.
• Properties are the appearance and behavior characteristics of a bean that can be
changed at design time. Builder tools introspect on a bean to discover its
properties and expose those properties for manipulation.
• Beans expose properties so they can be customized at design time. Customization
is supported in two ways: by using property editors, or by using more
sophisticated bean customizers.
• Beans use events to communicate with other beans. A bean that is to receive
events (a listener bean) registers with the bean that fires the event (a source bean).
Builder tools can examine a bean and determine which events that bean can fire
(send) and which it can handle (receive).
• Persistence enables beans to save and restore their state. After changing a bean's
properties, you can save the state of the bean and restore that bean at a later time
with the property changes intact. The JavaBeans architecture uses Java Object
Serialization to support persistence.
• A bean's methods are no different from Java methods, and can be called from
other beans or a scripting environment. By default all public methods are
exported.
Beans vary in functionality and purpose. You have probably met some of the following
beans in your programming practice:
This lesson guides you through the process of creating a bean pattern in the NetBeans
projects, introduces the user interface of the GUI Builder, and explains how to add your
bean object to the palette.
In the NetBeans IDE, you always work in a project where you store sources and files. To
create a new project, perform the following steps:
1. Select New Project from the File menu. You can also click the New Project
button in the IDE toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose the
Java Application type. Click the Next button.
3. Enter MyBean in the Project Name field and specify the project location. Do not
create a Main class here, because later you will create a new Java class in this
project.
4. Click the Finish button.
This figure represents the expanded MyBean node in the Projects list.
Creating a New Form
After creating a new project, the next step is to create a form within which the JavaBeans
components and other required GUI components, will be placed.
1. In the Projects list, expand the MyBean node, right-click on the <default
package> node and choose New|JFrame Form from the pop-up menu.
2. Enter MyForm as the Class Name.
3. Click the Finish button.
The IDE creates the MyForm form and the MyForm class within the MyBean application
and opens the MyForm form in the GUI Builder.
This figure represents the Projects list, where the MyForm class is located.
The GUI Builder Interface
When the JFrame form is added to your application, the IDE opens the newly-created
form in an Editor tab with a toolbar containing the following buttons:
• – Selection Mode enables you to select one or more objects in the Design
Area.
• – Connection Mode enables you to set a connection between objects by
specifying an event.
• – Preview Design enables you to preview the form layout.
• – Align commands enable you to align selected objects.
• – Change Resizability enables you to set up vertical and horizontal resizing.
When the MyForm form opens in the GUI Builder's Design view, three additional
windows appear, enabling you to navigate, organize, and edit GUI forms. These windows
include the following:
• Design Area. The primary window for creating and editing Java GUI forms.
Source and Design toggle buttons enable you to switch between view a class's
source code and a graphical view of the GUI components. Click on an object to
select it in the Design Area. For a multiple selection, hold down the Ctrl key
while clicking on objects.
• Inspector. Representation of a tree hierarchy of all the components in your
application. The Inspector highlights the component in the tree that is currently
being edited.
• Palette. A customizable list of available components containing groups for
Swing, AWT, Borders, and Beans components. This window enables you to
create, remove, and rearrange the categories displayed in the palette using the
customizer.
• Properties Window. A display of the properties of the component currently
selected in the GUI Builder, Inspector window, Projects window, or Files
window.
If you click the Source button, the IDE displays the application's Java source code in the
editor. Sections of code that are automatically generated by the GUI Builder are indicated
by blue areas. These blue areas are protected from editing in the Source view. You can
only edit code appearing in the white areas of the editor when in Source view. When you
make your changes in the Design View, the IDE updates the file's sources.
Creating a Bean
To create your own bean object and add it to the palette for the bean group, execute the
following procedure:
/**
* Getter for property yourName.
* @return Value of property yourName.
*/
public String getYourName() {
return this.yourName;
}
/**
* Setter for property yourName.
* @param yourName New value of property yourName.
*/
public void setYourName(String yourName) {
this.yourName = yourName;
}
8. Right-click the MyBean node in the MyBean project tree and choose Tools |Add
to Palette from the pop-up menu.
9. Select the Beans group in the Palette tree to add your bean.
Now you can switch to the Palette window by choosing Palette from the Windows menu
and make sure that the MyBean component was added to the Beans group.
So far you have created a bean, set the YourName property, and added this bean as a
component to the palette.
Now you can use the Free Design of the GUI Builder and add the MyBean component
and other standard Swing components to MyForm.
To summarize, in the previous steps you created a project, developed a JFrame form,
added a bean object and included it in your project as a non-visual component. Later in
this trail you will learn how to change properties for the bean component and handle
events by using the NetBeans GUI Builder.
18. Create a manifest, the JAR file, and the class file SimpleBean.class. Use the
Apache Ant tool to create these files. Apache Ant is a Java-based build tool that
enables you to generate XML-based configurations files as follows:
19. <?xml version="1.0" encoding="ISO-8859-1"?>
20.
21. <project default="build">
22.
23. <dirname property="basedir" file="${ant.file}"/>
24.
25. <property name="beanname" value="SimpleBean"/>
26. <property name="jarfile" value="${basedir}/${beanname}.jar"/>
27.
28. <target name="build" depends="compile">
29. <jar destfile="${jarfile}" basedir="${basedir}"
includes="*.class">
30. <manifest>
31. <section name="${beanname}.class">
32. <attribute name="Java-Bean" value="true"/>
33. </section>
34. </manifest>
35. </jar>
36. </target>
37.
38. <target name="compile">
39. <javac destdir="${basedir}">
40. <src location="${basedir}"/>
41. </javac>
42. </target>
43.
44. <target name="clean">
45. <delete file="${jarfile}">
46. <fileset dir="${basedir}" includes="*.class"/>
47. </delete>
48. </target>
49.
50. </project>
51. Load the JAR file. 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
your bean. You can use "Open Project" to add your 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.
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 your SimpleBean JAR file and follow the 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:
52. Inspect Properties and Events. The SimpleBean properties will appear in the
Properties window. For example, you can change a background property by
selecting another color. To preview your form, use the Preview Design button of
the GUI Builder toolbar. To inspect events associated with the SimpleBean
object, switch to the Events tab of the Properties window. You will learn more
about bean properties and events in the lessons that follow.
Lesson: Properties
In the following sections you will learn how to implement 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.
• 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.
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:
In previous lessons you learned how to create a simple property by using the NetBeans
GUI Builder. The following procedure shows how to create a simple property in detail:
Inspecting Properties
Select the MyBean component in the Other Components node in the Inspector window.
Now you can analyze the title property in the Properties window and change it. To
change the title property press the "..." button and enter any string you wish.
The following figure represents the title property set to the "The title" value.
The NetBeans GUI Builder enables you to restrict the changing of a property value. To
restrict the changing of the title property, right-click the title property in the Bean
Patterns node of the MyBean project. Select Properties from the pop-up menu and the
Properties window appears. Choose one of the following property access types from the
Mode combo box:
• Read/Write
• Read only
• Write only
The Read only property has only the get method only, while the Write only property has
only the set method only. The Read/Write type property has both of these methods.
Bound Properties
Sometimes when a Bean property changes, another object might need to be notified of the
change, and react to the change.
The accessor methods for a bound property are defined in the same way as those for
simple properties. However, you also need to provide the event listener registration
methods forPropertyChangeListener classes and fire a PropertyChangeEvent (in the
API reference documentation) event to the PropertyChangeListener objects by calling
their propertyChange methods
In order to listen for property changes, an object must be able to add and remove itself
from the listener list on the bean containing the bound property. It must also be able to
respond to the event notification method that signals a property change.
To create the title property as a bound property for the MyBean component in the
NetBeans GUI Builder, perform the following sequence of operations:
You can also modify existing code generated in the previous lesson to convert the title
and lines properties to the bound type as follows (where newly added code is shown in
bold):
import java.awt.Graphics;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.swing.JComponent;
/**
* Bean with bound properties.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];
if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}
Constrained Properties
A bean property is constrained if the bean supports the VetoableChangeListener(in the
API reference documentation) and PropertyChangeEvent(in the API reference
documentation) classes, and if the set method for this property throws a
PropertyVetoException(in the API reference documentation).
Constrained properties are more complicated than bound properties because they also
support property change listeners which happen to be vetoers.
The following operations in the setXXX method for the constrained property must be
implemented in this order:
The accessor methods for a constrained property are defined in the same way as those for
simple properties, with the addition that the setXXX method throws a
PropertyVetoException exception. The syntax is as follows:
Handling Vetoes
• Catching exceptions.
• Reverting to the old value for the property.
• Issuing a new VetoableChangeListener.vetoableChange call to all listeners to
report the reversion.
To create a constrained property, set the appropriate option in the New Property Pattern
form as shown on the following figure.
Note that the Multicast Source Event Pattern - vetoableChangeListener was added to the
Bean Patterns hierarchy.
You can also modify the existing code generated in the previous lesson to make the
title and lines properties constrained as follows (where newly added code is shown in
bold):
import java.io.Serializable;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
* Bean with constrained properties.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];
if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}
private void paintString( Graphics g, String str, int height )
{
if ( str != null )
g.drawString( str, 0, height );
}
}
Indexed Properties
To create an indexed property for your MyBean component, right-click the Bean Patterns
node and select Add|Indexed Property from the pop-up menu. Set up Non-Index Options
as shown in the following figure.
The code in the Source window will be changed automatically as follows:
import java.awt.Graphics;
import java.io.Serializable;
import javax.swing.JComponent;
/**
* Bean with simple property 'title'.
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
/**
* Holds value of property lines.
*/
private String[] lines;
/**
* Indexed getter for property lines.
* @param index Index of the property.
* @return Value of the property at index.
*/
public String getLines(int index) {
return this.lines[index];
}
/**
* Getter for property lines.
* @return Value of property lines.
*/
public String[] getLines() {
return this.lines;
}
/**
* Indexed setter for property lines.
* @param index Index of the property.
* @param lines New value of the property at index.
*/
public void setLines(int index, String lines) {
this.lines[index] = lines;
}
/**
* Setter for property lines.
* @param lines New value of property lines.
*/
public void setLines(String[] lines) {
this.lines = lines;
}
}
Add the following code to the MyBean.java component to present the user with a list of
choices. You can provide and change these choices at design time. (Newly added code is
shown in bold.)
import java.awt.Graphics;
import java.io.Serializable;
import javax.swing.JComponent;
/**
* Bean with a simple property "title"
* and an indexed property "lines".
*/
public class MyBean
extends JComponent
implements Serializable
{
private String title;
private String[] lines = new String[10];
if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height += step );
}
}
The following figure represents the lines property in the Properties window.
Notice that this property has a null value. To set up an alternative value, press the "..."
button. The form shown in the following figure enables you to add ten items for the
lines property list. First remove the default null items. Then add custom items to the list
by entering each item value into the Item field and pressing the Add button each time.
Lesson: Manipulating Events
Event passing is the means by which components communicate with each other.
Components broadcast events, and the underlying framework delivers the events to the
components that are to be notified. The notified components usually perform some action
based on the event that took place.
The event model that is used by the JavaBeans architecture is a delegation model. This
model is composed of three main parts: sources, events, and listeners.
The source of an event is the object that originates or fires the event. The source must
define the events it will fire, as well as the methods for registering listeners of those
events. A listener is an object that indicates that it is to be notified of events of a
particular type. Listeners register for events using the methods defined by the sources of
those events.
From the Properties lesson you discovered two event listeners. The
PropertyChangeListener(in the API reference documentation) interface provides a
notification whenever a bound property value is changed and the
VetoableChangeListener(in the API reference documentation) creates a notification
whenever a bean changes a constrained property value.
This example represents an application that performs an action when a button is clicked.
Button components are defined as sources of an event type called ActionEvent(in the
API reference documentation). Listeners of events of this type must register for these
events using the addActionListener method.
In addition, according to the requirements of the ActionListener class, you must define
an actionPerformed method, which is the method that is called when the button is
clicked.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* When receives action event notification, appends
* message to the JTextArea passed into the constructor.
*/
public void actionPerformed( ActionEvent event )
{
this.output.append( "Action occurred: " + event + '\n' );
}
}
class ActionTester {
public static void main(String args[]) {
JFrame frame = new JFrame( "Button Handler" );
JTextArea area = new JTextArea( 6, 80 );
JButton button = new JButton( "Fire Event" );
button.addActionListener( new ButtonHandler( area ) );
frame.add( button, BorderLayout.NORTH );
frame.add( area, BorderLayout.CENTER );
frame.pack();
frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOS
E );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
The JavaBeans API provides event-oriented design patterns to give introspecting tools
the ability to discover what events a bean can fire. For a bean to be the source of an
event, it must implement methods that add and remove listener objects for that type of
event. The design patterns for these methods are the following:
In the lesson "Using the NetBeans GUI Builder," you learned how to create a MyBean
component, add the yourName property, and design a simple form. Now you will set an
event by which a value entered in the JTextField component is stored in the yourName
property. Use the GUI Builder as follows to set such an event:
The Source Editor window is now displayed. Since the GUI Builder automatically
generates the code to connect the form's components, the following code will be added to
the MyForm class:
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.
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.
Any applet, application, or tool that uses that bean can then "reconstitute" it by
deserialization.
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.
Any class is serializable as long as that class or a parent class implements the
java.io.Serializable interface. Examples of serializable classes include Component,
String, Date, Vector, and Hashtable. Thus, any subclass of the Component class,
including Applet, can be serialized. Notable classes not supporting serialization include
Image, Thread, Socket, and InputStream. Attempting to serialize objects of these types
will result in an NotSerializableException.
The Java Object Serialization API automatically serializes most fields of a Serializable
object to the storage stream. This includes primitive types, arrays,and strings. The API
does not serialize or deserialize fields that are marked transient or static.
Controlling Serialization
You can control the level of serialization that your beans undergo. Three ways to control
serilization are:
The Serializable interface provides automatic serialization by using the Java Object
Serialization tools. Serializable declares no methods; it acts as a marker, telling the
Object Serialization tools that your bean class is serializable. Marking your class
Serializable means you are telling the Java Virtual Machine (JVM) that you have
made sure your class will work with default serialization. Here are some important points
about working with the Serializable interface:
• Classes that implement Serializable must have an access to a no-argument
constructor of supertype. This constructor will be called when an object is
"reconstituted" from a .ser file.
• You don't need to implement Serializable in your class if it is already
implemented in a superclass.
• All fields except static and transient fields are serialized. Use the transient
modifier to specify fields you do not want serialized, and to specify classes that
are not serializable.
To exclude fields from serialization in a Serializable object mark the fields with the
transient modifier.
If your serializable class contains either of the following two methods (the signatures
must be exact), then the default serialization will not take place.
You can control how more complex objects are serialized, by writing your own
implementations of the writeObject and readObject methods. Implement
writeObject when you need to exercise greater control over what gets serialized when
you need to serialize objects that default serialization cannot handle, or when you need to
add data to the serialization stream that is not an object data member. Implement
readObject to reconstruct the data stream you wrote with writeObject.
Use the Externalizable interface when you need complete control over your bean's
serialization (for example, when writing and reading a specific file format). To use the
Externalizable interface you need to implement two methods: readExternal and
writeExternal. Classes that implement Externalizable must have a no-argument
constructor.
The XMLEncoder class is assigned to write output files for textual representation of
Serializable objects. The following code fragment is an example of writing a Java
bean and its properties in XML format:
encoder.writeObject( object );
encoder.close();
The XMLDecoder class reads an XML document that was created with XMLEncoder:
What's in XML?
An XML bean archive has its own specific syntax, which includes the following tags to
represent each bean element:
or statements
<object class="javax.swing.JButton">
<void method="setText">
<string>Cancel</string>
</void>
</object>
The following code represents an XML archive that will be generated for the
SimpleBean component:
Lesson: Introspection
Introspection is the automatic process of analyzing a bean's design patterns to reveal the
bean's properties, events, and methods. 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.
Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to provide
introspection.
The BeanInfo (in the API reference documentation) 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. Then the
Introspector class applies the naming conventions to determine what properties the
bean has, the events to which it can listen, and those which it can send.
To open the BeanInfo dialog box, expand the appropriate class hierarchy to the bean
Patterns node. Right-click the bean Patterns node and choose BeanInfo Editor from the
pop-up menu. All elements of the selected class that match bean-naming conventions will
be displayed at the left in the BeanInfo Editor dialog box as shown in the following
figure:
Select one of the following nodes to view and edit its properties at the right of the dialog
box:
• BeanInfo
• Bean
• Properties
• Methods
• Event Sources
Special symbols (green and red) appear next to the subnode to indicate whether an
element will be included or excluded from the BeanInfo class.
If the Get From Introspection option is not selected, the node's subnodes are available for
inclusion in the BeanInfo class. To include all subnodes, right-click a node and choose
Include All. You can also include each element individually by selecting its subnode and
setting the Include in BeanInfo property. If the Get From Introspection option is selected,
the setting the properties of subnodes has no effect in the generated BeanInfo code.
The following attributes are available for the nodes for each bean, property, event
sources, and method:
For Event Source nodes, the following Expert properties are available:
• Unicast (read-only)
• In Default Event Set
Introspection Sample
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:
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:
You begin the process of editing these properties by clicking the property entry. Clicking
most of these entries will bring up separate panels. For 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.
To display the current property value "sample" within the Properties window, you need to
override isPaintable to return true. You then must override paintValue to paint the
current property value in a rectangle in the property sheet. Here's how ColorEditor
implements paintValue:
To support the custom property editor, override two more methods. Override
supportsCustomEditor to return true, and then override getCustomEditor to return a
custom editor instance. ColorEditor.getCustomEditor returns this.
In addition, the PropertyEditorSupport class maintains a PropertyChangeListener
list, and fires property change event notifications to those listeners when a bound
property is changed.
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. For 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
You have learned that builder tools provide support for you to create your own property
editors. What other needs should visual builders meet for complex, industrial-strength
beans? Often it is undesirable to have all the properties of a bean revealed on a single
(sometimes huge) property sheet. What if one single root choice about the type of the
bean rendered half the properties irrelevant? The JavaBeans specification provides for
user-defined customizers, through which you can define a higher level of customization
for bean properties than is available with property editors.
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. Sometimes properties are insufficient for representing a bean's
configurable attributes. Customizers are used where sophisticated instructions would be
needed to change a bean, and where property editors are too primitive to achieve bean
customization.
As stated in the specification, the purpose of the Extensible Runtime Containment and
Services Protocol is "to introduce the concept of a relationship between a Component
and its environment, or Container, wherein a newly instantiated Component is provided
with a reference to its Container or Embedding Context. The Container, or Embedding
Context not only establishes the hierarchy or logical structure, but it also acts as a
service provider that Components may interrogate in order to determine, and
subsequently employ, the services provided by their Context."
This section introduces extensible mechanisms and represents inheritance diagram of the
BeanContext API.
This section teaches how to use the BeanContextSupport class to provide the basic
BeanContext functionality.
This section teaches how to use service capability defined by the BeanContextServices
interface.
Additional Resources
In English, this means that there now exists a standard mechanism through which Java
developers can logically group a set of related JavaBeans into a "context" that the beans
can become aware of and/or interact with. This context, or "containing environment", is
known as the BeanContext.
There are two distinct types of BeanContext included in this protocol: one which
supports membership only (interface java.beans.beancontext.BeanContext) and one
which supports membership and offers services (interface
java.beans.beancontext.BeanContextServices) to its JavaBeans nested within.
The classes and interfaces relevant to the BeanContext API are listed in the following
diagrams. As you study the diagrams, take note of the BeanContext and
BeanContextServices interfaces, and that each has its own concrete implementation
that you can subclass or instantiate directly (classes
java.beans.beancontext.BeanContextSupport and
java.beans.beancontext.BeanContextServicesSupport respectively). Also take
note of the location of the java.beans.beancontext.BeanContextChild interface.
This is the interface that allows nested JavaBeans to become aware of their enclosing
BeanContext.
Bean Context #1: Containment Only
The "containment" portion of the Extensible Runtime Containment and Services Protocol
is defined by the BeanContext interface. In its most basic form, a BeanContext is used
to logically group a set of related java beans, bean contexts, or arbitrary objects.
JavaBeans nested into a BeanContext are known as "child" beans. Once nested, a child
bean can query its BeanContext for various membership information, as illustrated in the
following examples.
The following test programs, which are run from the command line, illustrate the use of
these methods.
File: Example1.java
import java.beans.beancontext.*;
report();
}
// Equality test
if (bean.getBeanContext() != null) {
boolean isEqual = (bean.getBeanContext()==context); // true
means both references point to the same object
System.out.println("Contexts are the same? " + isEqual);
}
System.out.println("===========================================
==");
}
}
Output:
=============================================
Is the context empty? true
Does the bean have a context yet? false
Number of children in the context: 0
Is the bean a member of the context? false
=============================================
Adding bean to context...
=============================================
Is the context empty? false
Does the bean have a context yet? true
Number of children in the context: 1
Is the bean a member of the context? true
Contexts are the same? true
=============================================
File: Example2.java
import java.beans.beancontext.*;
// A BeanContext
BeanContextSupport context = new BeanContextSupport();
// Many JavaBeans
BeanContextChildSupport[] beans = new
BeanContextChildSupport[100];
// Context now has 100 beans in it, get references to them all
Object[] children = context.toArray();
System.out.println("Number of objects retrieved from the
context: " + children.length);
}
}
Output:
Number of children in the context: 0
Number of children in the context: 100
Number of objects retrieved from the context: 100
File: Example3.java
import java.beans.beancontext.*;
import java.io.*;
BeanContextMembershipEvent Notification
The BeanContext API uses the standard Java event model to register listeners and
deliver events. For an overview of this standard event model, refer to Writing Event
Listeners. For details about handling specific events, see Writing Event Listeners.
File: MembershipTest.java
import java.beans.beancontext.*;
There are two event types that may be intercepted by such listeners:
JavaBeans can query their enclosing bean context for a list of available services, or ask
for a specific service by name. The service itself, however, is actually delivered by a
BeanContextServiceProvider. The provider can be any object that implements the
java.beans.beancontext.BeanContextServiceProvider interface. Services become
available in a context via the bean context's addService() registration method.
The Service
The service itself is best described by this paragraph from the specification:
File: DocumentBean.java
import java.beans.beancontext.*;
import java.io.*;
import java.util.*;
File: WordCountServiceProvider.java
import java.beans.beancontext.*;
import java.util.*;
import java.io.*;
File: WordCount.java
File: DocumentTester.java
import java.beans.beancontext.*;
import java.util.*;
File: Test.txt
by the WordCount
service.
Output: