Java Reference
In-Depth Information
For example, the various AWT and Swing components that have textual labels all have the
following pair of methods:
public String getText( );
public void setText(String newText);
You should use this set/get design pattern (set/get methods) for methods that control a bean.
Indeed, this technique is useful even in nonbean classes for regularity. The “bean containers”
for the APIs listed at the start of this section, generally use Java introspection (see
Chapter 23
)
to find the set/get method pairs, and some use these to construct properties edit-
ors for your bean. Bean-aware IDEs, for example, provide editors for all standard types (col-
ors, fonts, labels, etc.). You can supplement this with a
BeanInfo
class to provide or override
information.
The bare minimum a class requires to be usable as a JavaBean in a GUI builder is the follow-
ing:
▪ The class must implement
java.io.Serializable
.
▪ The class must have a no-argument constructor.
▪ The class should use the set/get paradigm.
▪ The class file should be packaged into a JAR file with the
jar
archiver program (see
Note that a JavaBean with no
required
inheritance or
implement
s is also called a POJO, or
“Plain Old Java Object.” Most new Java frameworks accept POJO components, instead of
(as in days of yore) requiring inheritance (e.g., Struts 1
org.struts.Action
class) or imple-
mentation of interfaces (e.g., EJB2
javax.ejb.SessionBean
interface).
Here is a sample bean that may be a useful addition to your Java GUI toolbox, the
La-
belText
widget. It combines a label and a one-line text field into a single unit, making it
easier to compose GUI applications. A test program in the online source directory sets up