Java Reference
In-Depth Information
This chapter explains how to use the JavaBeans API at the second level, or in
other words, it describes how to write beans. It covers the following topics:
•
Basic bean concepts and terminology
•
Requirements for the simplest beans
•
Packaging beans in JAR files
•
Providing additional information about beans with the
BeanInfo
class
•
Defining property editors to allow custom editing of bean properties
•
Defining bean customizers to allow customization of an entire bean
Note that the bean examples in this chapter are AWT components, for use with
Java 1.0 and 1.1. Although Swing components are now more commonly used than
AWT components, there are already many examples of custom Swing components
in Chapter 10,
Graphical User Interfaces
. Thus, the examples in this chapter do
double-duty as AWT examples as well as JavaBeans examples.
Bean Basics
We begin our discussion of beans with some basic concepts and terminology. Any
object that conforms to certain basic rules and naming conventions
*
can be a
bean; there is no
Bean
class that all beans are required to subclass. Many beans are
AWT components, but it is also quite possible, and often useful, to write “invisible”
beans that don't have an onscreen appearance. ( Just because a bean doesn't have
an onscreen appearance in a finished application doesn't mean that it can't be
visually manipulated by a beanbox tool, however.)
A bean exports properties, events, and methods. A
pr operty
is a piece of the
bean's internal state that can be programmatically set and queried, usually through
a standard pair of
get
and
set
accessor methods. A bean may generate
events
in
the same way that an AWT component, such as a
Button
, generates
ActionEvent
events. The JavaBeans API uses the same event model (in fact, it defines the event
model) used by Swing and AWT GUIs in Java 1.1 and later. See Chapter 10 for a
full discussion of this model. A bean defines an event by providing methods for
adding and removing event listener objects from a list of interested listeners for
that event. Finally, the
methods
exported by a bean are simply any
public
meth-
ods defined by the bean, excluding those methods used to get and set property
values and register and remove event listeners.
In addition to the regular sort of properties just described, the JavaBeans API also
provides support for indexed properties, bound properties, and constrained prop-
erties. An
indexed property
is any property that has an array value and for which
the bean provides methods to get and set individual elements of the array, as well
as methods to get and set the entire array. A
bound property
is one that sends out
a notification event when its value changes, while a
constrained property
is one
*
See Chapter 6 of
Java in a Nutshell
for a discussion of these rules and naming conventions. This
overview of JavaBeans is excerpted from that chapter.