0% found this document useful (0 votes)
104 views

SL291 JavaBeans Component Development Ig 1098

Uploaded by

Mok Jackie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

SL291 JavaBeans Component Development Ig 1098

Uploaded by

Mok Jackie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 564

JavaBeans Component Development

SL-291

Student Guide With Instructor Notes

Enterprise Services
MS BRM11
303 South Technology Court
Broomfield, Colorado 80021
U.S.A.

Part Number 805-1643-01


Revision A.4, October 1998
Copyright 1998 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303 U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution,
and decompilation. No part of this product or document may be reproduced in any form by any means without prior
written authorization of Sun and its licensors, if any.
Parts of this product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a
registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company Ltd. Third-party
software, including font technology in this product, is protected by copyright and licensed from Sun’s suppliers.
RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-
14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-1(a).
Sun, Sun Microsystems, the Sun logo, and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the
U. S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of
SPARC International, Inc. in the U. S. and other countries. Products bearing SPARC trademarks are based upon an
architecture developed by Sun Microsystems, Inc.
The OPEN LOOK® and Sun™ Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and
licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical
user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User
Interface, which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s
written license agreements.
X Window System is a product of the X Consortium, Inc.
DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS
AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH
DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Please
Recycle
Contents
About This Course......................................................................................xv
Course Overview .............................................................................. xvi
Course Map...................................................................................... xvii
Module-by-Module Overview ..................................................... xviii
Course Objectives............................................................................. xxii
Skills Gained by Module............................................................... xxiii
Guidelines for Module Pacing ..................................................... xxiv
Topics Not Covered......................................................................... xxv
How Prepared Are You?............................................................... xxvi
Introductions ................................................................................ xxviii
How to Use Course Materials ....................................................... xxix
How to Use the Icons...................................................................... xxxi
Typographical Conventions and Symbols ................................. xxxii
Overview of JavaBeans .............................................................................1-1
Relevance............................................................................................ 1-2
Objectives ........................................................................................... 1-3
What Is JavaBeans? ........................................................................... 1-4
A Java Component Model .......................................................1-4
Extension of the Java Platform ................................................1-5
What Is a Bean? ................................................................................. 1-6
Features of Beans.......................................................................1-6
Examples of Beans ....................................................................1-7
Classes and Beans .....................................................................1-7
Design Goals of the JavaBeans Model ........................................... 1-8
Compact .....................................................................................1-8
Easy to Create and Use.............................................................1-9
Fully Portable.............................................................................1-9
Flexible Build-time Component Editors ..............................1-10
Leverage Distributed Computing Mechanisms .................1-10
Component Architectures.............................................................. 1-11
Why Are They Useful? ...........................................................1-11
Services of Component Models ............................................1-12
Component Interface Publishing and Discovery ...............1-12

iii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Event Handling .......................................................................1-13
Persistence................................................................................1-13
Layout Control ........................................................................1-13
Application Builder Support .................................................1-13
Putting Beans Together .................................................................. 1-14
The BDK 1.0 Overview................................................................... 1-16
ActiveX as a Component Model ................................................... 1-18
Overview of ActiveX ..............................................................1-18
Advantages of ActiveX...........................................................1-20
Platform ....................................................................................1-21
Heavyweight or Lightweight ................................................1-21
Network Device Support .......................................................1-22
Interoperability........................................................................1-22
Software Versioning and Distribution.................................1-22
Distributed Computing..........................................................1-23
Performance .............................................................................1-23
Security .....................................................................................1-24
Check Your Progress ...................................................................... 1-25
Think Beyond .................................................................................. 1-26
The BeanBox ...............................................................................................2-1
Relevance............................................................................................ 2-2
Objectives ........................................................................................... 2-3
What Is the BeanBox? ....................................................................... 2-4
Running the BeanBox ...............................................................2-5
Windows of the BeanBox ................................................................. 2-6
ToolBox Window ......................................................................2-7
BeanBox Window......................................................................2-7
PropertySheet Window............................................................2-8
Design Mode in the BeanBox .......................................................... 2-9
Manipulating a Bean....................................................................... 2-10
Placing a Bean on the BeanBox Window.............................2-10
Selecting a Bean .......................................................................2-11
Moving a Bean.........................................................................2-12
Resizing a Bean........................................................................2-13
Changing Bean Properties – PropertySheet Window................ 2-16
Mechanics.................................................................................2-16
Effects on the BeanBox Window...........................................2-17
Changing Bean Properties – Customizers................................... 2-19
Bound Properties............................................................................. 2-22
Connecting Beans With Event Handlers ..................................... 2-26
Connecting Beans Through Events ......................................2-28
Saving and Restoring the BeanBox............................................... 2-31
Adding Your Own Bean to the ToolBox Window ..................... 2-33
JAR Files ...................................................................................2-33
Specifying a JAR File in an HTML File ................................2-35

iv JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Creating JAR Files...................................................................2-35
Using JAM................................................................................2-36
Sample Jamfile Makefile for JAM ......................................2-37
Exercise: Adding Your Own Bean to the ToolBox Window..... 2-39
Tasks .........................................................................................2-39
Experiment and Investigate........................................................... 2-41
BeanBox Summary.......................................................................... 2-42
Check Your Progress ...................................................................... 2-43
Think Beyond .................................................................................. 2-44
The Bean Event Model..............................................................................3-1
Relevance............................................................................................ 3-2
Objectives ........................................................................................... 3-3
What Is an Event? ............................................................................. 3-4
Delegation Model Overview ........................................................... 3-6
Sources and Listeners ...............................................................3-6
Propagating Notification of Events ........................................3-7
Simple Code Example ...................................................................... 3-8
Code Explanation......................................................................3-9
Categories of Events ....................................................................... 3-10
Obtaining Details About the Event .............................................. 3-12
Creating Your Own Event ............................................................. 3-13
Listeners ........................................................................................... 3-15
Event Listeners ........................................................................3-15
ActionListener Interface ....................................................3-16
Creating Your Own Listener Interface.................................3-17
Event Sources................................................................................... 3-18
Using Common Sources Provided by the AWT Package .3-18
Creating Your Own Source....................................................3-18
Identifying Sources .................................................................3-19
Multicast Syntax......................................................................3-20
Unicast Syntax .........................................................................3-21
Notifying All Listeners of an Event......................................3-22
Event Delivery Issues ..................................................................... 3-23
Synchronous Delivery ............................................................3-23
Multiple Listeners ...................................................................3-24
Example of Stock Market Beans............................................3-26
Running Stock Market Beans ................................................3-32
Exercise: Working With the Bean Event Model ......................... 3-33
Preparation...............................................................................3-33
Tasks .........................................................................................3-34
Exercise Summary...................................................................3-37
Check Your Progress ...................................................................... 3-38
Think Beyond .................................................................................. 3-39
Bean Properties...........................................................................................4-1
Relevance............................................................................................ 4-2

v
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Objectives ........................................................................................... 4-3
What Is a Bean Property?................................................................. 4-4
Types of Bean Properties .........................................................4-4
Properties and get/set Methods .................................................. 4-6
Read and Write Properties.......................................................4-6
Naming Conventions ...............................................................4-7
Simple Properties .............................................................................. 4-8
Defining Simple Properties......................................................4-8
Adding Simple Properties to a Bean ....................................4-10
Bound Properties............................................................................. 4-13
Defining Bound Properties ....................................................4-13
PropertyChangeSupport Class ...........................................4-14
Modifying the Property set Method ...................................4-14
Example of Creating a Bound Property...............................4-15
Bound Properties and the BeanBox Edit Menu ..................4-17
Recap of Bound Properties ............................................................ 4-19
Constrained Properties................................................................... 4-20
Overview ..................................................................................4-20
Defining Constrained Properties ..........................................4-21
Handling Vetoes......................................................................4-22
Using the VetoableChangeSupport Class.........................4-23
Registering Listeners ..............................................................4-24
Modifying the Property set Method ...................................4-24
Example of Creating a Constrained Property.....................4-25
Constrained Properties and Validation ....................................... 4-27
By Source or Listener? ............................................................4-27
Validating the Property Change ...........................................4-28
Constrained Properties and the BeanBox.................................... 4-29
Recap of Constrained Properties .................................................. 4-30
Properties and the BeanBox........................................................... 4-31
Discovering Bean Properties .................................................4-31
Properties on the PropertySheet Window...........................4-32
How a View Is Determined ...................................................4-35
Example of Views ...................................................................4-36
Exercise: Defining Bean Properties............................................... 4-37
Preparation...............................................................................4-37
Overview ..................................................................................4-38
Tasks .........................................................................................4-38
Exercise Summary...................................................................4-42
Check Your Progress ...................................................................... 4-43
Think Beyond .................................................................................. 4-44
Introspection ...............................................................................................5-1
Relevance............................................................................................ 5-2
Objectives ........................................................................................... 5-3
Introduction to Introspection .......................................................... 5-4

vi JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
What Problem Does Introspection Solve? .............................5-4
Introspection Addresses Key Issues.......................................5-6
Definitions..................................................................................5-8
The Introspector .............................................................................. 5-11
Summary of the Introspection Process ........................................ 5-12
Three Key Concepts of Introspection...................................5-12
Automatic Analysis ................................................................5-14
Naming Conventions for Properties ............................................ 5-15
Simple Properties ....................................................................5-16
Boolean Properties ..................................................................5-17
Indexed Properties..................................................................5-18
Naming Conventions for Events .................................................. 5-20
Multicast Event Sources .........................................................5-20
Unicast Event Sources ............................................................5-22
Naming Conventions for Methods............................................... 5-24
Capitalization Rules................................................................5-24
Naming Conventions for Methods............................................... 5-25
Beans.instantiate Method ....................................................... 5-26
Instantiation Supports Customized Beans and Applets ........... 5-27
Introspector.getBeanInfo Method........................................ 5-29
Information Discovered by getBeanInfo...........................5-30
SimpleBeanInfo Class ................................................................. 5-32
A BeanInfo Class That Affects Properties ............................... 5-34
Overriding the getPropertyDescriptors Method.........5-36
Limiting Visible Properties....................................................5-37
The PropertyDescriptor Class .......................................5-37
The setDisplayName Method.............................................5-38
The setBound Method ..........................................................5-38
Using getAdditionalBeanInfo.................................................. 5-39
How It Can Be Used ...............................................................5-39
A BeanInfo Class That Affects Methods ...........................5-41
Details of How a BeanInfo Is Processed..................................... 5-43
Probe BeanInfo Classes for Descriptor Information ......5-43
Apply Reflection and Naming Conventions.......................5-44
Available BeanInfo Methods ...................................................... 5-45
Reflection and JavaBeans ............................................................... 5-50
Advantages Provided by Reflection.....................................5-50
Major Classes of the Reflection API .....................................5-52
Additional Information on Introspection.................................... 5-53
Security .....................................................................................5-54
Final Words on Introspection........................................................ 5-55
Exercise: Creating a BeanInfo File ............................................ 5-57
Preparation...............................................................................5-57
Tasks .........................................................................................5-58
Exercise Summary...................................................................5-60
Check Your Progress ...................................................................... 5-61

vii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Think Beyond .................................................................................. 5-62
Persistence ...................................................................................................6-1
Relevance............................................................................................ 6-2
Objectives ........................................................................................... 6-3
Goals for Bean Storage ..................................................................... 6-4
General Java Object Storage ....................................................6-4
Bean Storage...............................................................................6-5
Java Object Serialization................................................................... 6-6
Serializable Interface...........................................................6-6
Classes That Are Serializable ..................................................6-7
What Is and Is Not Saved ................................................................ 6-8
Bean Properties and Internal State .........................................6-8
Pointers and Event Adapters ..................................................6-8
Fields Automatically Serialized ..............................................6-9
Fields Not Serialized.................................................................6-9
The Keyword transient ......................................................6-10
Input and Output Interfaces.......................................................... 6-11
Saving Beans to Streams ................................................................ 6-12
ObjectOutputStream Class..................................................6-12
Example of Code Syntax ........................................................6-13
Retrieving Beans From Streams .................................................... 6-14
ObjectInputStream Class....................................................6-14
Example of Code Syntax ........................................................6-15
Creating a Java Beans Prototype................................................... 6-16
Packaging a Prototype Bean ..................................................6-17
Deserialization and Class Loaders ............................................... 6-18
Using Beans.instantiate() ..............................................6-19
Beans.instantiate() Methodology.................................6-19
Recap of Persistence........................................................................ 6-20
Exercise: Creating a New Bean Through Serialization.............. 6-21
Tasks .........................................................................................6-21
Exercise Summary...................................................................6-23
Check Your Progress ...................................................................... 6-24
Think Beyond .................................................................................. 6-25
Customization.............................................................................................7-1
Relevance............................................................................................ 7-2
Objectives ........................................................................................... 7-3
What Can You Do Through Customization?................................ 7-4
Can You Extend Editor Support to New Property Types? .7-6
When Is a Property-Specific Editor Not Enough?................7-7
Property Sheets and Property Editors ........................................... 7-8
Property Sheets..........................................................................7-8
Property Editors ........................................................................7-9
Review of Views.............................................................................. 7-10
The PropertyEditor Interface..................................................... 7-11

viii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Description of the PropertyEditor Interface....................7-11
The PropertyEditor Interface..................................................... 7-12
How to Implement the PropertyEditor Interface..........7-12
Overview of the PropertyEditor Methods ......................7-13
Implementing the PropertyEditor Interface ...................7-15
Null Argument Constructor..................................................7-16
Supporting setValue() ........................................................7-17
Add and Remove PropertyChangeListeners ......................7-18
Sample PropertyEditor for a MultipleLine Label....................... 7-19
Display Style Requirements .......................................................... 7-23
Sample Editor – BoolEditor ...................................................7-27
Extending PropertyEditorSupport.......................................... 7-29
When to Use.............................................................................7-29
Making Your Property Editor Known ......................................... 7-31
Naming Conventions .............................................................7-32
BeanInfo for the MultilineLabel Bean ................................7-33
Recap of Property Editors.............................................................. 7-35
Exercise: Creating a Property Editor............................................ 7-36
Preparation...............................................................................7-36
Tasks .........................................................................................7-37
Exercise Summary...................................................................7-39
Customizers ..................................................................................... 7-41
Customizer Use .......................................................................7-41
Characteristics of Customizers..............................................7-42
Naming Conventions .............................................................7-42
Implementing a Customizer Class .............................................. 7-43
Implementation Requirements .............................................7-43
Defining BeanInfo .................................................................7-44
Extending Component/Implementing Customizer..........7-45
Providing a Null Argument Constructor ............................7-45
Adding and Removing PropertyChangeListeners .......7-46
Defining setObject()...........................................................7-47
Example of a Customizer............................................................... 7-48
Recap of Customizers..................................................................... 7-50
Exercise: Creating a Customizer ................................................... 7-51
Preparation...............................................................................7-51
Tasks .........................................................................................7-52
Exercise Summary...................................................................7-53
Check Your Progress ...................................................................... 7-54
Think Beyond .................................................................................. 7-55
Event Adapters ...........................................................................................8-1
Relevance............................................................................................ 8-2
Objectives ........................................................................................... 8-3
What Is an Event Adapter?.............................................................. 8-4
Adapters Used in the BeanBox ....................................................... 8-5

ix
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Example of an Adapter Hookup Class ..................................8-6
Types of Adapters............................................................................. 8-8
Common Uses of Adapters......................................................8-9
Diagrams ..................................................................................8-10
Differentiating Adapters From Normal Listeners...................... 8-12
Case With No Adapters .........................................................8-12
Case With Adapters................................................................8-13
Demultiplexing Adapter Example ............................................... 8-14
Application Window ..............................................................8-14
Description of Application ....................................................8-15
Appl.java Code .....................................................................8-16
Widgets.java Code...............................................................8-17
ActionAdapter.java Code..................................................8-18
Multiplexing Adapters ................................................................... 8-20
Overview of Multiplexer Exercise ........................................8-20
Exercise: Working With Adapters ................................................ 8-23
Preparation...............................................................................8-23
Tasks .........................................................................................8-24
Exercise Summary...................................................................8-30
Check Your Progress ...................................................................... 8-31
Think Beyond .................................................................................. 8-32
Distributed Computing
With Beans...................................................................................................9-1
Relevance............................................................................................ 9-2
Objectives ........................................................................................... 9-3
Motivating Scenarios for Distributed Bean Programming ......... 9-4
Areas of Familiarity ..................................................................9-4
Future Enterprise JavaBeans ...................................................9-6
Applications for Distributed Beans ........................................9-6
JavaSoft Distributed Computing Technologies .......................... 9-10
Definition of JDBC .......................................................................... 9-11
JDBC API and Drivers............................................................9-11
Overview of JDBC Architecture.................................................... 9-12
BeanBox JDBC Bean........................................................................ 9-14
Advantages of Database-Related Beans ..............................9-16
Definition of RMI ............................................................................ 9-17
BeanBox RMI Bean.......................................................................... 9-18
RMI Architecture Overview .......................................................... 9-19
Transport Layer.......................................................................9-20
Remote Reference Layer ........................................................9-20
RMI Stubs and Skeletons .......................................................9-21
rmic Command.......................................................................9-21
rmiregistry Application ....................................................9-21
RMI Exercise Code.......................................................................... 9-22
Exercise Description ...............................................................9-22

x JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Source Files Provided .............................................................9-23
Interfaces ..................................................................................9-24
Implementation Classes .........................................................9-26
Server Code Overview ...........................................................9-30
CORBA/JavaIDL (Optional) ......................................................... 9-32
Exercise: Creating an RMI Client Bean ........................................ 9-33
Preparation...............................................................................9-33
Tasks .........................................................................................9-34
Exercise Summary...................................................................9-37
Check Your Progress ...................................................................... 9-38
Think Beyond .................................................................................. 9-39
Beans Outside of the
BeanBox .....................................................................................................10-1
Relevance.......................................................................................... 10-2
Objectives ......................................................................................... 10-3
Options for Building Beans ........................................................... 10-4
Building a Bean From Scratch ...............................................10-4
Inheriting From a Bean...........................................................10-5
Subclassing a Bean and Adding BeanInfo.........................10-6
Composing a Bean From Other Beans ...............................10-10
From a Serialized Prototype ................................................10-11
Creating Applets and Applications With Beans ...................... 10-14
Using a Builder Tool (IDE/RAD Tool) ..............................10-15
Coding Programmatically ...................................................10-16
Scripting .................................................................................10-16
Issues for Applets That Are Beans.............................................. 10-17
Delivering Your Beans ................................................................. 10-18
A Set of .class Files ............................................................10-18
How Are JAR Files Used?....................................................10-19
JAR File Review.....................................................................10-19
Using JAR Files in HTML ....................................................10-20
JAR Files With a Digital Signature ............................................. 10-24
Definition................................................................................10-24
Why Use Digital Signatures?...............................................10-24
Comparing Handwritten and Digital Signatures.............10-25
Digital Signatures and Beans in JAR Files.........................10-25
Digital Signatures and Certificates.....................................10-26
Fitting the Pieces Together ..................................................10-28
Security and Cryptography .................................................10-31
What Tools Are Involved?...................................................10-33
For More Information...........................................................10-34
Loading and Instantiating a Bean............................................... 10-35
Coding Possibilities ..............................................................10-36
Instantiating a Bean in an Applet .......................................10-37
Instantiating a Bean in an Application ..............................10-37

xi
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Instantiating a Bean From a Serialized Stream .................10-38
Roles of Class and ClassLoader .............................................. 10-39
The Class Class ....................................................................10-39
The ClassLoader Class .......................................................10-41
Sample Code .................................................................................. 10-43
Instantiating a Bean in an Applet .......................................10-43
Instantiating a bean in an Application...............................10-45
Hooking Beans Together.............................................................. 10-50
Exercise: Writing Applets or Applications With Beans........... 10-52
Preparation.............................................................................10-52
Tasks .......................................................................................10-53
Exercise Summary.................................................................10-61
Check Your Progress .................................................................... 10-62
Think Beyond ................................................................................ 10-63
Business Environment for
JavaBeans...................................................................................................11-1
Relevance.......................................................................................... 11-2
Objectives ......................................................................................... 11-3
“Write once, run anywhere” ......................................................... 11-4
Component-Based Software Review............................................ 11-5
Business Influences .................................................................11-5
Major Elements........................................................................11-6
Review of Services ..................................................................11-7
Bridging JavaBeans to Other Component Models ..................... 11-8
ActiveX Bridge.........................................................................11-9
InfoBus Technology ...................................................................... 11-10
InfoBus Technology and JavaBeans ...................................11-11
InfoBus Architecture Overview ..........................................11-11
Development Environments ....................................................... 11-12
Integrated Development Environments ............................11-12
Rapid Application Development........................................11-13
Visual Application Builder Tools ............................................... 11-14
What Are They?.....................................................................11-14
Examples ................................................................................11-15
Deciding on the Tool for You ..............................................11-19
Check Your Progress .................................................................... 11-20
Think Ahead .................................................................................. 11-21
Transitional Beans
(Optional) ..................................................................................................12-1
Relevance.......................................................................................... 12-2
Objectives ......................................................................................... 12-3
What Are Transitional Beans?....................................................... 12-4
Compatibility With JavaBeans FCS ......................................12-4
Browser Support for JavaBeans ............................................12-5
Creating a Transitional Bean ......................................................... 12-6

xii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Marker Classes ........................................................................12-6
Developer Rules ......................................................................12-8
Example of Transitional Beans.................................................... 12-10
Sample Description...............................................................12-10
ButtonPushEvent Class ......................................................12-11
Listener Interface...................................................................12-12
OurButton Class ...................................................................12-13
JellyBean Class ...................................................................12-15
Flipper Applet .......................................................................12-16
Things to Remember..................................................................... 12-18
Check Your Progress .................................................................... 12-19
Event 1.0.x to Event 1.1
Conversion .................................................................................................A-1
Event Handling ................................................................................ A-2
Event Handling Before JDK 1.1..............................................A-2
Event Handling in JDK 1.1 .....................................................A-2
Converting 1.0 Event Handling to 1.1........................................... A-3
Making a Component a Listener ................................................... A-6
Jamfile and Manifest
Templates ................................................................................................... B-1
Listing for Jamfile.template...................................................... B-2
Listing for manifest.tmp............................................................... B-3
JAM Overview...........................................................................................C-1
JAM .................................................................................................... C-2
Features .....................................................................................C-2
Custom JAM Rules for Java Programs.......................................... C-3
Glossary ......................................................................................... Glossary-1
Index .....................................................................................................Index-1

xiii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
About This Course

Course Goal
JavaBeans Component Development provides you with the knowledge
and skills necessary for creating reusable software components using
the JavaBeans™ API (application programming interface). This
includes an understanding of: Bean properties, introspection and
reflection, Bean events and event handling, customization, and
persistence.
✓ You should use this module to get the students excited about this course.

✓ With regard to the overheads: To avoid confusion among the students, it is very important
to tell them that the page numbers on the overheads have no relation to the page numbers
in their course materials. They should use the title of each overhead as a reference.

✓ The strategy provided by the “About This Course” is to introduce students to the course
before they introduce themselves to you and one another. By familiarizing them with the
content of the course first, their introductions will have more meaning in relation to the
course prerequisites and objectives.

✓ Use this introduction to the course to determine how well students are equipped with the
prerequisite knowledge and skills. The pacing chart on page xxiv enables you to
determine what adjustments you need to make in order to accommodate the learning
needs of students.

xv
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Overview

With JavaBeans, application developers can create and combine re-


usable software building blocks into an application. A Bean
component built once from the API according to standard can be
integrated without further code changes into any environment where
the Java technology is supported. In addition, a Java™ bean forms the
communication bridge between a Java application and non-Java
technologies such as ActiveX, OpenDoc, or LiveConnect.

Developers taking this class will gain the essential knowledge and
skills to create JavaBean components that run on every Java virtual
machine and can be reused in the widest variety of development tools,
containers, and popular environments available.

xvi JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Map

Each module begins with a course map that enables you to see what
you have accomplished and where you are going in reference to the
course goal. A complete map of this course is shown below.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

About This Course xvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Module-by-Module Overview

● Module 1 – Overview of JavaBeans

The purpose of this module is to provide an explanation of what


JavaBeans and a Bean are, discuss the design goals of JavaBeans,
and explain what a component model is and why JavaBeans is a
component model.

● Module 2 – The BeanBox

This module uses the discussion of the BeanBox to introduce the


key topics of this course: properties and introspection (how they
are related, how they work), persistence, customization, property
sheets, property editors, BeanInfo classes, and builder tools.
✓ This module can be done as a self-study. Walk around the room as the students read
information and perform the short exercises included throughout the module.

Lab exercise: An investigative lab; work with the BeanBox, its


Bean palette, property sheet, and menus. In so doing, many of
the major features of Beans will be discovered.

xviii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Module-by-Module Overview

● Module 3 – The Bean Event Model

The purpose of this module is to familiarize you with the Java


Developer’s Kit (JDK™) 1.1 event model that is used by the
JavaBeans API: events, event sources, event listeners, and how
they work together for event handling.

Lab exercise: Create simple Beans and specify one Bean as a


listener to another Bean’s events.

● Module 4 – Bean Properties

The purpose of this module is to familiarize you with Bean


properties: what they are, how to create them, what types there
are, and how to change them.

Lab exercise: Work with different Bean property types by creating


components with simple, bound, and constrained properties, and
by providing get/set methods for these properties.

● Module 5 – Introspection

This module helps you understand how methods, properties,


and events are discovered in the Beans that you write.

Lab exercise: Create a BeanInfo class for a Bean created in a


previous exercise.

● Module 6 – Persistence

In this module, serialization and how it relates to Bean storage is


discussed.

Lab exercise: Write the appropriate mechanisms to persist Beans.

● Module 7 – Customization

Property sheets, property editors, and the Customizer class are


presented in this module.

Lab exercise: Create a customizer and property editor for some of


the Beans created in previous exercises.

About This Course xix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Module-by-Module Overview

● Module 8 – Event Adapters

The purpose of this module is to show how event adapters can


be used to provide more control over the handling of events
under the new event model.

Lab exercise: Create an adapter to handle events for several Bean


components.

● Module 9 – Distributed Computing With Beans

This module demonstrates the importance of Bean development


with respect to distributed computing technologies.

Lab exercise: Use Beans on the client side to make method calls
through remote method invocation (RMI) to a remote Java
application.

xx JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Module-by-Module Overview

● Module 10 – Beans Outside of the BeanBox

In this module, you will learn what code you need to write to
have your Beans run in an applet or an application.

Lab exercise: Create an applet or application that uses Bean


components written in a previous exercise and provides the same
functionality as the Beans which were connected in the BeanBox.

● Module 11 – Business Environment for JavaBeans

This module explains how JavaBeans fits into the business


environment with other component models and builder tools.

● Module 12 – Transitional Beans (Optional)

This module provides training on Bean development for those


who need to create Bean components for applications (such as
browsers) that do not support JDK 1.1 yet.

About This Course xxi


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Objectives

Upon completion of this course, you will be able to:

● Define a Bean component and describe why JavaBeans is a Java


component model.

● Package JavaBeans components into JAR (Java Archive) files, add


them to the BeanBox tool palette, and test them in the BeanBox.

● Given a class that implements a specific listener interface, write


the appropriate event handling methods.

● Create a JavaBeans component with bound or constrained


properties.

● Describe how the introspection process works, including the


relevance to naming conventions and to menu options displayed
in the BeanBox.

● Write the required persistence mechanisms for a customized Bean


component.

● Control the configuration and customization of Bean components


through customizer classes, property editors, property sheets, and
BeanInfo classes.

● Create event adapters to modify event delivery between sources


and listeners.

● Develop Bean components as intelligent front-ends to network


servers using a network access mechanism (such as JDBC [Java
database connectivity], RMI, or CORBA [common object request
broker architecture]).

● Create applets or applications using existing Bean components.

● Explain how JavaBeans components can be used with existing


component models such as ActiveX and OpenDoc.

● Create a transitional Bean.


✓ You might ask the students how many signed up for this course because of the
information in the SES (Sun Educational Services) course catalog, what their knowledge
and expectations of the objectives stated there are, and use this information as a tool to
manage your time in covering the material in this course.

xxii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Skills Gained by Module

The skills for JavaBeans Component Development are shown in column 1


of the matrix below. The black boxes indicate the main coverage for a
topic; the gray boxes indicate the topic is briefly discussed.

Module
1 1 1
Skills Gained 1 2 3 4 5 6 7 8 9
0 1 2

Define a Bean component and describe why JavaBeans is a


Java component model.

Package JavaBeans components into JAR files, add them to


the BeanBox tool palette, and test them in the BeanBox.

Given a class that implements a specific listener interface,


write the appropriate event handling methods.

Create a JavaBeans component with bound or constrained


properties.

Describe how the introspection process works, including the


relevance to naming conventions and to menu options
displayed in the BeanBox.

Write the required persistence mechanisms for a customized


Bean component.

Control the configuration and customization of Bean


components through customizer classes, property editors,
property sheets, and BeanInfo classes.

Create event adapters to modify event delivery between


sources and listeners.

Develop Bean components as intelligent front-ends to


network servers using a network access mechanism (such as
JDBC, RMI, or CORBA).

Create applets or applications using existing Bean


components.

Explain how JavaBeans components can be used with


existing component models such as ActiveX and OpenDoc.

Create a transitional Bean.

✓ Refer students to this matrix as you progress through the course to show them the
progress they are making in learning the skills advertised for this course.

✓ Module 12 is optional and thus does not cover any skills that are essential to the course.

About This Course xxiii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Guidelines for Module Pacing

The table below provides a rough estimate of pacing for this course.

Module Day 1 Day 2 Day 3 Day 4

About This Course A.M.


Overview of JavaBeans A.M.
The BeanBox A.M
P.M.
The Bean Event Model P.M.
Bean Properties A.M.
Introspection P.M.
Persistence A.M.
Customization A.M
P.M.
Event Adapters P.M.
Distributed Computing With Beans A.M.
Beans Outside of the BeanBox P.M.
Business Environment for JavaBeans P.M.
Transitional Beans P.M.

xxiv JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Topics Not Covered

This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services (SES):

● Object-oriented concepts – Covered in OO-100: Object-Oriented


Technology and Concepts.

● Object-oriented design and analysis – See OO-120: Object-Oriented


Design and Analysis.

● Java language constructs – Refer to SL-110: Programming for


Beginners Using Java or SL-275: Java Programming.

● Distributed programming APIs – Distributed programming APIs


from JavaSoft™ are covered in
SL-301: Distributed Programming With Java.

Refer to the SES catalog for specific information and registration.

About This Course xxv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
How Prepared Are You?

✓ Students may or may not have experience in software component development.

To be sure you are prepared to take this course, can you answer the
questions shown on the above overhead in the affirmative?

● If you are an experienced Java programmer, you will be familiar


with AWT event handling, layout managers, Java language
constructs, creating classes and subclasses, and other tasks that are
necessary for writing JavaBeans components in this course.
✓ Event handling experience under JDK 1.0.2 or JDK 1.1 is fine.

● Having programmed in the Java language, you should understand


how to implement interfaces and handle exceptions. The
delegation event model (in JDK 1.1) that is used by JavaBeans
requires implementing listener interfaces. You will also use
methods that require you to handle exceptions that are thrown.

xxvi JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
How Prepared Are You?

● You should have experience programming in an object-oriented


language (such as Java or C++) so that you understand what it
means to create an object, inherit from a class, extend a class, and
so forth. These terms and concepts are used in this class.

● If you have experience designing an object-oriented model for a


problem, you will be able to conceptualize the functionality,
behavior, and attributes of the Beans you need to program in this
course, and write object-oriented Java code for these Beans.

● If you are at ease learning new APIs, you will be comfortable


learning the main concepts of the JavaBeans API presented in this
course.

● If you learn best from code examples and technical explanations,


you will be able to program the lab exercises based on the
explanations and examples presented in the lecture.

Based on affirmative answers to the above questions, this course was


designed to present the major concepts of the JavaBeans API with code
examples and give you practical experience programming these
concepts in lab exercises.
✓ If any students indicate they cannot do the above, meet with them at the first break to
decide how to proceed with the class. Do they want to take the class at a later date? Is
there some way to get the extra help needed during the week?

✓ It might be appropriate here to recommend resources from the SES catalog that provide
training for topics not covered in this course.

About This Course xxvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Introductions

Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.

xxviii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
How to Use Course Materials

To enable you to succeed in this course, these course materials employ


a learning model that is composed of the following components:

● Course Map – Each module starts with an overview of the content


so you can see how the module fits into your overall course goal.

● Relevance – The relevance section for each module provides


scenarios or questions that introduce you to the information
contained in the module and provoke you to think about how the
module content relates to your interest in creating reusable
JavaBeans software components.

● Overhead Image – Reduced overhead images for the course are


included in the course materials to help you easily follow where
the instructor is at any point in time. Overheads do not appear on
every page. Moreover, if a topic continues from an odd-numbered
page to an even-numbered page, a 25 per cent reduced image
(instead of a 50 per cent reduced image) is used to indicate the
instructor is still on the overhead from the previous page.

About This Course xxix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
How to Use Course Materials

● Lecture – The instructor will present information specific to the


topic of the module. This information will help you learn the
knowledge and skills necessary to succeed with the exercises.

● Exercise – Lab exercises will give you the opportunity to practice


your skills and apply the concepts presented in the lecture. The
sample code presented in the lecture should help you in
completing the lab exercises.

● Check Your Progress – Module objectives are restated, sometimes


in question format, so that before moving on to the next module
you are sure that you can accomplish the objectives of the current
module.

● Think Beyond – Thought-provoking questions are posed to help


you apply the content of the module or predict the content in the
next module.

xxx JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
How to Use the Icons

The following icons are used in this course to represent various


training elements and alternative learning resources:
Demonstration - Indicates a demonstration is recommended at this
time.

Discussion – Indicates a small-group or class discussion on the current


topic is recommended at this time.

Exercise objective – Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.

Additional resources – Indicates additional reference materials are


available.

About This Course xxxi


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Typographical Conventions and Symbols

The following table describes the typographical conventions and


symbols used in this course:

Typeface or
Meaning Example
Symbol

AaBbCc123 The names of commands, Edit your .login file.


files, and directories; on- Use ls -a to list all files.
screen computer output. system% You have
mail.

AaBbCc123 What you type, system% su


contrasted with Password:
on-screen computer
output.
AaBbCc123 Command-line To delete a file, type rm
placeholder—replace filename.
with a real name or
value.
AaBbCc123 Book titles, new words or Read Chapter 6 in User’s
terms, or words to be Guide.
emphasized. These are called class
options.
You must be root to do
this.

xxxii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Notes to the Instructor

Philosophy
The JavaBeans Component Development course has been created to allow
for interactions between the instructor and the student as well as
among the students themselves. In an effort to enable you to
accomplish the course objectives easily, and in the time frame given, a
series of tools have been developed and support materials created for
your discretionary use.

A consistent structure has been used throughout this course. This


structure is outlined in the “Course Goal” section. The suggested flow
for each module is:

1. Location of module in the course map


2. Context questions/module rationale
3. Module objectives
4. Lecture information with appropriate overheads
5. Lab exercises
6. Discussion: either as a whole class or in small groups

To allow for flexibility and to give time for meaningful discussions


during the “relevance” periods, the lectures, and the small-group
discussions, a timing table is included in “General Timing
Recommendations.”

Course Tools
To enable you to follow this structure, the following supplementary
materials are provided with this course:

● Relevance

These questions or scenarios set the context of the module. It is


suggested that you ask these questions and discuss the answers.
The answers are provided only in the instructor’s guide.

About This Course xxxiii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Notes to the Instructor

Course Tools (Continued)


● Course Map

The course map allows the students to get a visual picture of the
course. It also helps students know where they have been, where
they are, and where they are going. The course map is presented
initially in the “About This Course” section in the student’s
guide. The course map is then displayed at the beginning of each
module with the appropriate module highlighted.

● Lecture Overheads

Overheads for the course are provided in two formats:

The paper-based format can be copied onto standard


transparencies and used on a standard overhead projector. These
overheads are also provided in the student’s guide.

The Web browser–based format is in HTML and can be projected


using a projection system which displays from a workstation.
This format allows the students to view the overhead
information on individual workstations. It also allows better
random access to the overheads.

● Small-Group Discussion

After the lab exercises, it is a good idea to debrief the students.


You can gather them back into the classroom and have them
discuss their discoveries, problems, and issues in programming
the solution to the problem in small groups of four or five, one-
on-one, or one-on-many.

xxxiv JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Notes to the Instructor

Course Tools (Continued)


● General Timing Recommendations

Each module contains a “Relevance” section after the course


map. This section may present a scenario relating to the content
presented in the module, or it may present questions that
stimulate students to think about the content that will be
presented. Engage the students in relating experiences or posing
possible answers to the questions. Spend no more that 10–15
minutes on this section.

Lecture Lab Total Time


Module
(Minutes) (Minutes) (Minutes)
Preface 35 No exercises 35
Module 1 30 No exercises 30
Module 2 90 (self-paced or lab done throughout the lecture) 90
Module 3 60 60 120
Module 4 60 70 130
Module 5 90 60 150
Module 6 30 50 80
Module 7 70 70 140
Module 8 40 65 105
Module 9 60 60 120
Module 10 60 70 130
Module 11 30 No exercises 30
Module 12 (Optional) 40 No exercises 40

About This Course xxxv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Notes to the Instructor

Course Tools (Continued)


● Module Self-Check

Each module contains a checklist for students under “Check Your


Progress.” Give them a little time to read through this checklist
before going on to the next lecture. Ask them to see you
regarding items they do not feel comfortable checking off.

xxxvi JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Instructor Setup Notes

Purpose of This Guide


This guide provides all of the details that you need to know to initially
set up the classroom environment and to prepare the environment for
each class offering.

Minimum Resource Requirements

Network

There are no special network requirements. The following type of


programming lab will suffice:

● All workstations are networked together using NFS.

● A server machine is available from which student workstations


can mount exported directories.

Hardware

● A server machine with ample disk space for loading the majority
of the required software; directories containing loaded software
are to be exported to student workstations for mounting

● Printer for the students to print their programs

● SPARCstation™ 4 or better for each student to include:

▼ Diskette drive or other tape drive so students can copy their


work to take with them at the end of the course

▼ 32 Mbytes RAM

▼ 535–600 Mbytes of disk space

● Overhead projection system that can project HTML slides

About This Course xxxvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Instructor Setup Notes

Minimum Resource Requirements

Software

● Solaris™ 2.4 or later

● JDK 1.1 or later

● JDK 1.1 or later docs directory

● HotJava™ browser (supports JDK 1.1 and Beans)

● Netscape Navigator™ 3.01 browser if you plan to enable testing of


transitional Beans (optional module)

● Bean Developer’s Kit (BDK) April ‘97 or later

● Labfiles for this course

Copies of Work Done in Exercises


At the end of this course, students will have created various Java
Beans components from their work in the lab exercises.

Mention to students at the beginning of the course that they can copy
all their work to a tape or diskette to take home with them. This will
give them time to purchase a tape or diskette if they did not bring one
with them.

xxxviii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Instructor Setup Notes

Assumptions About the Lab


The following assumptions are made about the lab used for this
course:

● There is one workstation per student in the lab.

● Each student workstation is set up with login accounts for this


course (for example, beans, or something similar).

● Students work at the same machine throughout the course.

About This Course xxxix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Setting Up for a SL-291 Class

Preparing for SL-291 Classes


The following procedures must be completed before each SL-291 class:

On Each Student Workstation

Below is an overview of what must be installed on each student


workstation. See page xlv for details.

● Install the appropriate operating system as described in the


“Minimum Resource Requirements” section on all student
workstations.

● Set up student accounts with a copy of the lab files to use in this
course in each account on every workstation.

● Install the latest BDK (1.0-November ‘97 or later) in every account


on all workstations.

Note – Students will be creating directories under


$HOME/SL291files/work for the Beans that they write and test in the
BeanBox. So each of their source files will include a package statement,
package SL291.BeanName. The JAR files created for their Beans will
be located in the jars directory of their BDK.

● Install the jam utility for creating JAR files (included with
distribution files in the $HOME/SL291files/bin directory).

● Mount/map appropriate directories from the server machine.

● Set environment variables. Solaris 2.6 users have special


requirements - see the Solaris 2.6 users and JDK 1.1 section under
Configuring the Classroom.

xl JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Setting Up for a SL-291 Class

Preparing for SL-291 Classes

On the Server Machine

Below is an overview of what needs to be installed on the server


machine. See page xlix for details.

● Installation of the appropriate operating system as described in the


“Minimum Resource Requirements” section

● Installation of the latest JDK docs

● Installation of the latest Java Developer’s Kit (JDK) 1.1 or higher

● Installation of the Netscape Navigator 3.01 browser (if you intend


to provide for the testing of transitional Beans)

● Installation of the appropriate browser to run JDK 1.1 code and


Beans as described in the “Minimum Resource Requirements –
Software” section

Note – Any browser can be used to view the API docs provided with
the JDK. However, at the time of this writing, Netscape
Communicator 4.0, Microsoft Internet Explorer, and HotJava browser
support JDK 1.1 and Beans developed with BDK 1.0. If you think you
might be doing Module 12, “Transitional Beans,” and that you may
have students who will want to do some work creating transitional
Beans, you will also want to have a Java-enabled browser that does not
yet support JDK 1.1.

About This Course xli


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Setting Up for a SL-291 Class

Preparing for SL-291 Classes

Projection System and Workstation

If you have a projection system for projecting HTML slides and are
planning to use the HTML slides, you need to do the following:

● Install the HTML overheads on the workstation connected to the


projection system so you can display them with a browser during
lecture.

To install the HTML overheads on the machine connected to your


overhead projection system, copy the HTML and images
subdirectories provided in the SL291_OH_revX_XXXX directory
to any directory on the overhead workstation machine. These
files use approximately 2 Mbytes of disk space.

Display the overheads in the browser by choosing


Open ➤ File and typing the following in the Selection field of the
pop-up window:

/location_of_HTML_directory/
OH.Title.doc.html

Note – To install a browser on the overhead workstation machine,


follow the instructions for installing the browser on the lab machines
on page xlix.

● Set up an overhead-projection system that can project instructor


workstation screens.

Note – This document does not describe the steps necessary to set up
an overhead projection system because it is unknown what will be
available in each training center. This setup is the responsibility of
each training center.

xlii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Files

All of the course files for this course are available from the
education.central server in the file SL291_revX_XXXX.tar.Z.
Each component below can also be accessed separately from
education.central.

Note – You can use ftp or the education Web site,


http://education.central/courses/courses/ja.html, to
download the files from education.central. Either of these
methods requires you to know the user ID and password for ftp
access. See your manager for these if you have not done this before.

Course Components
The SL-291 course consists of the following components:

● Instructor’s Guide

The SL291_IG_revX_XXXX directory contains the FrameMaker


files for the instructor’s guide (Student Guide With Instructor
Notes). The ART directory is required for printing this guide.

● Student’s Guide

The SL291_SG_revX_XXXX directory contains the FrameMaker


files for the student’s guide. The ART directory is required for
printing this guide.

● Art

The SL291_ART_revX_XXXX directory contains the supporting


raster images and artwork for the student and instructor guides.
This directory is needed in order to print the student and
instructor guides and should be located in the same directory as
SL291_IG_revX_XXXX and SL291_SG_revX_XXXX.

About This Course xliii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Course Files

Course Components (Continued)


● Instructor notes

The SL291_IN_revX_XXXX directory contains the document


Instructor Setup Notes. This document is also appended as
conditional text at the end of the preface FrameMaker document
for this course.

● Overheads

The SL291_OH_revX_XXXX directory contains the instructor


overheads. There are both HTML and FrameMaker versions of
the overheads.

● Lab files

The SL291_LF_revX_XXXX directory contains the following


subdirectories:

▼ SL291files – A directory containing the lab files and


solutions to be used in the exercises for this course, as well as
the examples used in the student’s guide. These lab files should
be copied to each student account on each workstation.

You will need approximately 2.5 Mbytes of disk space for the
lab files.

▼ SL291files/bin – A directory containing a jam executable


and jam HTML files to be contained in the PATH variable of
each student account.

▼ recapRef.ps – A PostScript™ file that contains the recap


boxes summarizing the major concepts of JavaBeans
component development.
✓ It would be helpful to students to print copies of this file and hand them out for students
to work from and take with them to use as a reference. The FrameMaker document is
located in the SL291_IN directory.

xliv JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Configuring the Classroom

Student Workstations

Recommended Partitions and Sizes for Solaris

Each machine should have 535–600 Mbytes of disk space partitioned


as follows and installed with Solaris 2.4:

/ 20 Mbytes
swap 75 Mbytes
/usr 230 Mbytes
/opt 70 Mbytes
/var 70 Mbytes
/home Remainder

Note – If you do not have a server machine, each student workstation


will require a 1-Gbyte disk for installing the JDK, JDK docs directory,
and the browsers.

Recommended Partitions and Sizes for Windows

Each machine should have a 1-Gbyte drive with a minimum of 200


Mbytes before starting the installation. More is always better. Placing
the API documentation on a server will reduce the drive space
required on the client machine.

Student Accounts

It is sufficient for this course to install one account on each workstation


(such as user beans with no password), and require students to use
the same workstation throughout the course.

Note – Follow the procedures used at your training center for creating
student accounts on each workstation.

About This Course xlv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Configuring the Classroom

Student Workstations

Lab Files in Each Account

After you have created the student accounts, copy the contents of the
labfiles directory to each account on every student workstation
(approximately 2.3 Mbytes).

Bean Developer Kit

Download the latest BDK from http://www.javasoft.com/beans


and install the contents in every student account on every workstation.

Each student account should have a file structure similar to that shown
in the following figure:

SL291files

work BDK bin


02-beanbox ... 10-outsideBB

and so on
Source files
Jamfiles course_examples solutions

jars demo beanbox

sunw
run command

and so on

xlvi JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Configuring the Classroom

Student Workstations

jam Command

The distribution includes jam in the $HOME/SL291files/bin


directory. directory. Ensure this directory is in the student’s path.

Note – If using Solaris 2.6, see the section called Solaris 2.6 users and
JDK 1.1.

Mounting Server Directories

Mount the directories from the server that contain the JDK, JDK docs,
and browsers. For example, the server could share a central directory
and the clients’ vfstab or auto_master could mount that directory as
/SL291 or /javafiles.

Environment Variables

For each student account, set the following environment variables in


the appropriate startup file for the student account. This is done in the
.cshrc file for C shell and the .profile or .kshrc file for K shell. If
using Solaris 2.6, refer to the section called Solaris 2.6 users and JDK 1.1.

● Set JAVA_HOME to the installation directory of the JDK (or the


mount point for the JDK software). Do not set this environment
variable if using Solaris 2.6.

● Set the PATH variable to include the path to the JDK’s bin
directory (for accessing the commands javac, java, and so on),
and the absolute directories for the executables of the browsers
you installed (or the appropriate mount point directories).

● Set the BDK_HOME variable to include $HOME/SL291files/BDK.

● Set the CLASSPATH variable to include $HOME/SL291files/work


and . (for the current directory).

About This Course xlvii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Configuring the Classroom

Student Workstations

Note – As of JDK 1.1, inclusion of $JAVA_HOME/lib/classes.zip is


no longer required, but the jam utility requires that JAVA_HOME is set.
Solaris 2.6 users, please refer to the section called Solaris 2.6 users and
JDK 1.1.

Note – Change the BDK/beanbox/run.bat CLASSPATH line to:


set CLASSPATH=classes;%CLASSPATH%

Solaris 2.6 Users and JDK 1.1

Solaris 2.6 users intending to use the installed /usr/java


environment can not have the environment variable JAVA_HOME
set due to the way the Java package is installed on Solaris 2.6. Since the
jam utility (supplied in the $HOME/SL291files/bin) requires
JAVA_HOME to be set, a wrapper script (called jamsol26) is supplied
to work around this problem. The script is not necessary on 2.6 if
JAVA_HOME and PATH are set to override the JDK that comes installed
with the OS.

By default, the script sets JAVA_HOME=/usr/java. If necessary, edit


the jamsol26 script to change the path for the JDK installation (or
the mount point for the JDK software).

To use the wrapper script, perform the following command.

mv jam to jam0
mv jamsol26 to jam

xlviii JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Configuring the Classroom

Server Machine
After installing the operating system, install the following software in
directories that are exported to and mounted by student workstations.

Java Developer’s Kit and docs Directory

Pull the latest JDK (JDK 1.1 or later) and JDK doc files from
http://www.javasoft.com/nav/download/index.html and follow
the installation instructions provided to install the JDK and docs.

Together, the JDK and JDK docs directory use approximately 34


Mbytes of disk space.

Note – The JDK and doc files can be installed on one machine. The
remaining machines in the lab can then mount the directory with the
JDK software.

Browsers

You can use any browser to view the JDK API documents. Download
the browser from the Web and follow the installation instructions
provided with the browser to install it on each student workstation.

Note – The Netscape Navigator Gold Browser 3.01 uses almost 6


Mbytes of disk space.

JDK 1.1 Browser

Install the browser chosen to host the JDK 1.1 applets.

About This Course xlix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
l JavaBeans Component Development
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
About This Course li
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Overview of JavaBeans 1

Course Map
The main goal of this module is to help you understand the JavaBeans
architecture as a component model.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

1-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.

Discussion – The following questions are relevant in understanding


what JavaBeans is all about:

1. In order to reuse software, what must a developer understand?

✓ The developer must understand how to use the software, its functionality, properties, and
methods. This understanding can be provided by good documentation. This requires that
the documentation be written and then read. Sometimes this does not happen. In addition,
the use of standard naming conventions combined with encapsulation can add to the
reusability of software.

✓ You might also briefly discuss how hardware or automotive systems are developed from
components to help set the scene for this module.

2. What advantage does the Java component model offer over other
component models?

✓ The Java component model (JavaBeans) provides greater portability because it is created
in the Java programming language. It is also enhanced by functionality provided by the
Java Platform, such as object serialization, cut-copy-paste on the desktop, network
awareness, and distributed computing mechanisms such as RMI and JavaIDL, to name a
few. In addition, all JDK 1.1 components are simple beans.

1-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Objectives

Upon completion of this module, you will be able to:

● Define JavaBeans.

● Describe the services every component model must provide.

● Explain why JavaBeans is a Java component model.

● Describe the design goals for JavaBeans.

● Explain what a bean is.

● Compare and contrast JavaBeans and ActiveX as component


models.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans API 1.0 Specification. [Online]. Available:


http://splash.javasoft.com/beans/spec.html.

● Beans Development Kit (BDK 1.0). [Online]. Available:


http://splash.javasoft.com/beans/bdk_download.html.

● JavaBeans: A Component Architecture for Java. [White paper].


Available:
http://splash.javasoft.com/beans/WhitePaper.html
[1996, July].

● Component-Based Software with JavaBeans and ActiveX. [White


paper]. Available:
http://www.sun.com/javastation/whitepapers/javabeans/
javabean_ch1.html [1996, October].
✓ This course does not expect you (the instructor) to be an expert in ActiveX. However,
information comparing ActiveX and JavaBeans is included here because students will ask.
More information on ActiveX, the ActiveX bridge, and magazine articles can be obtained
from the JavaSoft Web site.

Overview of JavaBeans 1-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

What Is JavaBeans?

JavaBeans is a portable, platform-independent component model


written in the Java programming language. The JavaBeans architecture
was built through a collaborative industry effort and enables
developers to write reusable components in the Java programming
language.

A Java Component Model


A component model enables developers to create software pieces
called components that can be combined to create applications. The
JavaBeans architecture builds on the software component model. A set
of APIs describes a component model for a particular language.
Component models usually provide a common set of services. These
services are described on page 11.
✓ This is why working with the JavaBeans architecture is referred to as component
development.

1-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
What Is JavaBeans?

JavaBeans APIs
The JavaBeans 1.0 API specification describes the core specification for
the JavaBeans component architecture. The Javadoc documentation for
the JavaBeans classes and interfaces is provided in the doc directory of
the Beans Development Kit (BDK 1.0).
✓ Refer to the URL locations under "References" on page -3.

Extension of the Java Platform


The JavaBeans component model adds new levels of flexibility and
reuse to the existing Java Platform. Independent bean components can
be used and reused in different ways to create new applications.
Developers can connect different JavaBeans components together
(using event passing by builder tool applications or custom code) for
communication and interaction.

Overview of JavaBeans 1-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

What Is a Bean?

A bean can be described as “a reusable software component that can


be manipulated visually in a builder tool.”

Features of Beans
Bean components can vary in the functionality they provide, however,
the following features are typical in all beans:

● Introspection – Controls the publishing and discovery of bean


operations and properties.

● Customization – Enables a developer to customize the appearance


and behavior of a bean at design time.

● Event – Enables beans to communicate and connect to each other


using the bean event model.

1-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
What Is a Bean?

Features of Beans (Continued)


● Properties – Enables developers to program the choices for the
appearance and behavior of a bean.

● Persistence – Enables storing and restoring the state of a bean in a


standard way.

Examples of Beans
Beans vary in functionality and purpose. Some examples of beans
include:

● GUI (graphical user interface) widgets

Note – All JDK 1.1 AWT components are simple bean components.

● Non-visual beans, such as a spelling checker

● An animation applet

● A spreadsheet application
✓ Note that applets and applications can themselves be beans.

Classes and Beans


What is the difference between a bean and a Java class? Beans
themselves are classes (or a group of classes) that follow the naming
conventions set forth in the JavaBeans API specification for properties,
methods, events, and so on. This enables the introspection process to
analyze a bean and discover its properties and behaviors; otherwise,
builder tools would not be able to “learn” what is necessary about
beans to be able to hook beans together to create more complex
behavior or functionality.

Overview of JavaBeans 1-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

Design Goals of the JavaBeans Model

To fully appreciate the JavaBeans component model, it is beneficial to


understand the major design goals.

Compact
The JavaBeans architecture was designed to leverage much of the
functionality provided with the Java Platform so that the JavaBeans
architecture would remain a very compact model.

Leverage Strengths of Java Platform

The JavaBeans architecture uses the introspection and reflection


technology of the Java Developer’s Kit (JDK 1.1) to discover classes,
methods, and properties. In addition, JDK 1.1 AWT components are
themselves simple beans.

1-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Design Goals of the JavaBeans Model

Compact (Continued)
The JavaBeans component model also uses the JDK 1.1 Serialization
API for bean persistence, and the cut-copy-paste mechanisms of the
AWT.
✓ Serialization, distributed mechanisms, reflection mechanisms, and so forth are not part of
the JavaBeans API, but the JDK itself. Other component models may actually have to build
this functionality into their model.

Easy to Create and Use


The JavaBeans APIs are relatively uncomplicated and simple
components are very easy to create. Yet you can also build more
complex components with the JavaBeans architecture.

Fully Portable
JavaBeans components have a distinct advantage over other
component models: they are not bound to a particular platform,
container, or component model. Because the JavaBeans model is
written in the Java programming language, and the JavaBeans API is
part of the standard Java Platform, JavaBeans components are fully
portable.

Overview of JavaBeans 1-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

Design Goals of the JavaBeans Model

Flexible Build-time Component Editors


The JavaBeans architecture enables developers to create build-time
property sheets, inspectors, and editors for their components. Many
property editors are provided with the BDK, but developers may want
to provide an editor better suited to the functionality of the
component’s properties.

For example, instead of a long list of properties on a property sheet, a


component developer might organize the properties at one level, with
further details available at another level.

Leverage Distributed Computing Mechanisms


The Java Platform provides several distributed computing
mechanisms, such as RMI and JavaIDL (CORBA IDL). JavaBeans
component developers can take advantage of these robust mechanisms
when creating components for use in distributed applications.

1-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

Component Architectures

Why Are They Useful?


Building large applications can be slow and expensive. By creating
components, developers have portable, reusable code with which to
work. Components can be developed quickly to meet market
opportunities and needs. The functionality provided in each
component can be combined with future components in new ways
unforeseen at development time.

Overview of JavaBeans 1-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

Component Architectures

Services of Component Models


All component models must provide the following major services:

● Component interface publishing and discovery

● Event handling

● Persistence

● Layout control

● Application builder support

Component Interface Publishing and Discovery


The interface publishing and discovery feature of a component model
enables other components to learn of the existence and interfaces of a
new component. This enables components to interact with each other.

In the JavaBeans model, this feature is provided by introspection and


reflection.

1-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Component Architectures

Event Handling
Event passing is the mechanism by which components communicate
with each other. Components broadcast events and the underlying
framework delivers the events to the components that want to be
notified. The notified component usually takes some action based on
the event that took place.

Persistence
Component models provide a mechanism for persistence that enables
the state of components to be stored in a non-volatile place for later
retrieval.

In JDK 1.1, this feature is provided by the Serialization API.

Layout Control
Layout control in component models is two-fold:

● Control of the visual appearance of a component

● Mechanisms and services for determining layout of components


within a container
✓ Most component layout control is done by giving a component a non-overlapping
rectangular space.

Application Builder Support


All component models provide interfaces for application builder
support. With these interfaces, tools determine the properties and
behaviors of arbitrary components. Builder tools usually provide
mechanisms that help developers to quickly assemble components
into an application. These mechanisms can include tool palettes,
inspectors, editors, a means of specifying the relationship between
events and event handling methods, and debuggers.

Overview of JavaBeans 1-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

Putting Beans Together

To get an idea of how beans can be used to build an application,


suppose you have the following beans:

● Graphing or charting bean – A bean that charts data sent to it.

● Random number generator bean – A bean that generates a random


number between two given values.

● Animation bean – An animation of Duke doing cartwheels.

● Timer bean – A bean that triggers an alarm at regular intervals and


generates ticks.

Suppose you connect these beans so that when the timer bean triggers
an alarm, the random number generator produces a new number
between two specified values. This new number is then sent to the
animation bean to control the speed at which Duke does cartwheels in
the animation. The graphing bean graphs the speed of the Duke over
time (intervals are based on the timer bean).

1-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Putting Beans Together

This produces a new application—the speed at which Duke does


cartwheels is random and is charted over time. These beans may not
have been written to be connected in this way, but it demonstrates
how components can be connected to create new applications.

Overview of JavaBeans 1-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

The BDK 1.0 Overview

The Beans Development Kit (BDK) is intended to support the early


development of JavaBeans components and to act as a standard
reference base for both component developers and tool vendors. The
BDK provides a reference bean container, the BeanBox and a variety of
reusable example source code (in the demo and beanbox
subdirectories) for use by JavaBeans component and tool developers.

The BDK is an add-on to the JDK. After downloading a compliant


JDK, acquire the BDK from the JavaSoft Web site. Although it will
work with any 1.1.X JDK, it is recommended that it be used with JDK
1.1.5 or later. The BDK is qualified for Solaris 2.4, Solaris 2.5, Windows
95, and Windows NT 4.0. However the BDK is a pure Java
development kit and should run on any JDK 1.1 enabled system.

1-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
The BDK 1.0 Overview

Figure 1-1 shows the BDK BeanBox which is used by developers to test
their beans before deploying them in an actual tool. Using the BeanBox
to test Beans is very similar to how developers use the appletviewer to
test applets before implementing them in a full-blown browser.

Hashed boundary
around the BeanBox
Bean indicates
the currently selected
Bean

Figure 1-1 The BeanBox as an Illustration of Bean Palettes, Builder


Tools, Layouts, and Bean Property Display

Overview of JavaBeans 1-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

ActiveX as a Component Model

Overview of ActiveX
ActiveX is a component model from Microsoft (and thus provides the
five major services of a component model). The ActiveX model
supports components written in other languages, but these other
components must be accessed through ActiveX, not their native APIs.

1-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
ActiveX as a Component Model

Overview of ActiveX (Continued)


As an example, a JavaBeans component is wrapped inside ActiveX
API binary code. This enables it to work with all Microsoft
components, but it is not portable outside of the Win32 environment.

Component-based
application
ActiveX API
OLE OLE
control document

OCX Java
Components control Bean

Figure 1-2 ActiveX Encapsulates Heterogeneous Components


Inside a Windows API1

The BDK includes an JavaBeans ActiveX bridge that allows JavaBeans


components to function within an ActiveX container. The bridge is
available at no cost from JavaSoft.

1. Diagram taken from the white paper “Component-Based Software With JavaBeans
and ActiveX.”

Overview of JavaBeans 1-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

ActiveX as a Component Model

Advantages of ActiveX
ActiveX is built on a mature technology (Object Linking and
Embedding [OLE] technology) and there are many components
available. As mentioned previously, the ActiveX model supports
components from different programming languages, providing access
to the rich functionality of Microsoft components.
✓ OCX definition from http://www.zdnet.com/wsources/content/topics/ocx.html: An OLE
Custom control. An object-oriented custom control that is developed under OLE. OCXs
are created as separate executable modules and are dynamically linked at runtime. An
OCX object allows the application more control and customization of the object’s
functions than does a standard OLE object.

1-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

JavaBeans and ActiveX Comparison

A comparison between ActiveX and JavaBeans as component models


can be made with regard to the following areas:

Platform
ActiveX is platform-specific—it can only be used where Microsoft has
ported the framework and components. JavaBeans components are
platform neutral because they are written in the Java programming
language.

Heavyweight or Lightweight
ActiveX components require a heavyweight application to provide a
container in order to run. JavaBeans components are considered
lightweight and require only the Java interpreter or an applet viewer
(such as a browser or the Applet Viewer).

Overview of JavaBeans 1-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

JavaBeans and ActiveX Comparison

Network Device Support


The lightweight design of JavaBeans components enable beans to run
on a wide range of network devices (from supercomputers to
JavaStations™ and cellular phones). In contrast, ActiveX components
are unsuitable for use in thin clients because they require a
heavyweight application in order to run.

Interoperability
Unlike the ActiveX model, JavaBeans components do not encapsulate
components from other vendors. A JavaBeans component
interoperates with other architectures (ActiveX components included)
through a two-way bridge.

Software Versioning and Distribution


The ActiveX model requires application servers to maintain a copy of a
component for each platform supported. This makes versioning,
distribution, and updating difficult. In the JavaBeans model, however,
only one copy of a bean needs to be maintained. In addition, automatic
software distribution is part of the Java network computing platform.
Thus, the administration of software (versioning and distribution) is
simplified.

1-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
JavaBeans and ActiveX Comparison

Distributed Computing
ActiveX components use Distributed Common Object Model (DCOM)
in object-oriented distributed computing applications. However,
CORBA is being used in the industry as the standard in distributed
computing for network connectivity in enterprise-wide applications.
The JavaBeans model leverages on the Java Platform, which includes
the CORBA standard for object-based distributed computing. This
implies that through CORBA, Beans can communicate and access
components written in many different languages on a wide range of
computing platforms.

Performance
To be efficient in the ActiveX model, existing OLE components must
be rewritten. ActiveX components enjoy some performance advantage
over JavaBeans components because of their inherent native code.
However, with just-in-time (JIT) compilers and HotSpot compilers for
Java, performance of Beans is improving and quickly becoming a non-
issue.

Note – Existing ports of ActiveX components to non-Windows


environments have not shown desirable performance.

Overview of JavaBeans 1-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1

JavaBeans and ActiveX Comparison

Security
The ActiveX model relies on digital signatures on components. Digital
signatures verify the source of a component, but do not limit the
functionality accessible by the component. Trojan horses and viruses
coded into third-party components can invade a system.

In contrast, the JavaBeans model employs several levels of security.


Signed components, as well as different levels of control over
untrusted components, are used. Because of the Java environment
restrictions placed on accessing local resources, invasion by Trojan
horses or viruses is unlikely.
✓ The intent here is to address the ActiveX topic up front, and not say much more about it.
The discussion here should be short. Do not let students get carried away on this. Refer
them to the URL on the ActiveX bridge (http://splash.javasoft.com/beans/bridges).

1-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish or answer the following:

❑ Define the JavaBeans component model.

❑ What services must every component model provide?

❑ Why is JavaBeans called a Java component model?

❑ Describe the design goals for the JavaBeans architecture.

❑ What is a bean?

❑ Compare and contrast JavaBeans and ActiveX as component


models.

Overview of JavaBeans 1-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
1
Think Beyond

Suppose you have written a few JavaBeans components. You now


want to test how well your beans work. Can you do this within the
BDK? Do you need a third-party builder tool?

1-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
The BeanBox 2

Course Map
This module covers how to run, work with, and load your beans in
the BeanBox.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

2-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Relevance

✓ Pose the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – As you begin to create bean components, you will be


asking yourself the following questions. The answers to these
questions are relevant to the BeanBox discussion in this module:

1. What is involved with testing bean components?

✓ Testing a bean involves several things:


• Successful compilation of the bean

• Proper display of the bean, if it is a visual component (most beans are)

• Proper handling of events (this usually requires interaction with other beans)

2. How does a developer test bean components?


✓ The BeanBox is one tool for testing bean components. Other builder tools can be used as
well, such as writing small applications or applets that instantiate your beans, display
them, and check event handling. Writing applications or applets for testing beans is not
efficient for testing beans, and you might not have a builder tool. Thus, the BeanBox is
provided with the JavaBeans Developer’s Kit for the purpose of testing beans.

Module Presentation Options

✓ This module can be presented in the lab or left as self-paced.

• Presented in lab – The objective is to have students actually do what you are
presenting so that they better understand the content. You will have to monitor the
class carefully so that students do not start doing other things on their own as you
move through the presentation. Restrict students to what is asked of them as each
piece of information is presented. After everything is covered, you might give them
15–20 minutes to experiment with the beans provided with the BDK. Try to keep the
total time limited to about 1.5 hours total lecture and lab time.
• Self-paced – Let students read the module, and do the short exercises as they
progress through the module. You then can walk around the room, monitoring
progress and answering questions. This alternative is especially attractive if you find
it difficult to control what students do when they perform the short exercises as you
present the material.

2-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Objectives

Upon completion of this module, you will be able to:

● Explain the purpose of the BeanBox.

● Move and resize beans on the Composition window of the


BeanBox.

● Change bean properties using the PropertySheet window of the


BeanBox.

● Register a bean as the listener of an event generated by another


Bean in the Composition window.

● Save and restore the current state of the BeanBox.

● Explain what a Java archive (JAR) file is and how it can be used.

● Create a JAR file for a prewritten bean and add it to the ToolBox
window of the BeanBox.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● The BeanBox, provided with the BDK in the doc/beanbox.html


file.

● JAR Guide. [Online]. Available:


http://www.javasoft.com:80/products/jdk/1.1/docs/
guide/jar/jarGuide.html.

● Manifest Format Specification. [Online]. Available:


http://www.javasoft.com:80/products/jdk/1.1/docs/
guide/jar/manifest.html.

The BeanBox 2-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

What Is the BeanBox?

The BeanBox is a test container for testing your bean components. In


addition, there are various sample beans provided in the demo
directory of the Beans Developer Kit (BDK) that you can try out and
connect to other beans in different ways to experiment with and learn
about bean features and behaviors.

Note – The BeanBox is itself a bean component—it acts as a container


for other beans.

The BeanBox is not a builder tool. Using the BeanBox, you cannot
generate code to create applications or applets for what you have
connected together in the BeanBox.
✓ Installation of the BDK is not covered since it is very straightforward—download the BDK
from the JavaSoft Web pages and run the downloaded script.

2-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
What Is the BeanBox?

Running the BeanBox


The BDK provides a directory called beanbox that contains a file called
run.sh (for UNIX® platforms) and a file called run.bat (for
Windows 95 and NT platforms).
✓ Assuming that the bin directory of the Java Developer Kit 1.1 (JDK 1.1) is part of your
PATH, the BeanBox will run correctly.

Starting and Running the BeanBox

Demonstration - This demonstration will guide you through starting


and running the BeanBox.

1. Change directory to SL291files/BDK/beanbox.

2. Start the BeanBox:


% run.sh&

The BeanBox 2-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Windows of the BeanBox

When the BeanBox runs, three windows are displayed:

Hashed boundary
around the BeanBox
Bean

Figure 2-1 Windows of the BeanBox

2-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Windows of the BeanBox

✓ Note that when the windows are displayed, they all appear in a row: the ToolBox, the
BeanBox, and then the PropertySheet window.

ToolBox Window
The ToolBox window, also referred to as the bean palette, displays the
current beans available to the BeanBox.
✓ When the BeanBox is started (using run.sh), JAR files located in the jars directory are
read and the beans in these JAR files are loaded into the ToolBox window. If you modify
your beans and rebuild the JAR files, quit the current BeanBox and restart using run.sh.
Your JAR files are reread with the changes you made.

BeanBox Window
The BeanBox window, also called the Composition window, is where a
bean from the bean palette is placed. Sizing, moving, changing
properties, using the BeanBox menus, and so forth are carried out
relative to the bean currently selected in this window.

The BeanBox 2-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Windows of the BeanBox

PropertySheet Window
The PropertySheet window displays the properties of the bean
currently selected in the BeanBox window.

In Figure 2-1, the PropertySheet window is displaying the properties


of the BeanBox itself, which is the currently selected bean.

Note – A selected bean in the BeanBox window is indicated by a


hashed boundary.

2-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Design Mode in the BeanBox

When the BeanBox is started, it is in design mode; the ToolBox


window and the PropertySheet window are part of the design mode.
To disable design mode, choose View ➤ Disable Design Mode. The
ToolBox and PropertySheet windows are no longer displayed, and the
BeanBox window is displayed without the hashed boundary around
any bean.

Within design mode, a bean can be customized by changing its


properties, possibly resizing it, moving it, or hooking it up to other
beans through events.

When design mode is disabled (runtime mode), a bean must be able to


function as it was created and customized to do (it must behave
properly). The Tool window and PropertySheet window are not visible
when the BeanBox is in runtime mode.

The BeanBox 2-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Manipulating a Bean

Placing a Bean on the BeanBox Window


To place a bean from the ToolBox window into the BeanBox window,
just click SELECT on the name of the bean in the ToolBox window (the
mouse pointer changes to a cross-hair +) and then click in the BeanBox
window where the bean is to be displayed.

Note – The bean is displayed centered around the location of the


mouse click in the BeanBox window.

2-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Manipulating a Bean

Placing Beans in the BeanBox Window


Demonstration - In this demonstration, you will create instances of
beans in the BeanBox window.

1. Add a jellyBean bean to the BeanBox window.

2. Add a juggler bean to the BeanBox window.

3. Add two ExplicitButton beans to the BeanBox window.

Note – You can clear the BeanBox window of all beans by choosing
File ➤ Clear.

Selecting a Bean
A bean in the BeanBox window is selected by clicking on the
boundary area of the bean. When the bean is selected, a hashed border
is displayed around the bean.

Note – When a new bean is added to the BeanBox window, it becomes


the currently selected bean.

The BeanBox 2-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Manipulating a Bean

Moving a Bean
Once a bean is selected, you can move it by positioning the mouse on
the hashed boundary (the mouse pointer changes to four-way arrows
) and then pressing SELECT while you drag the bean to the new
position.

Figure 2-2 Moving a Bean

2-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Manipulating a Bean

Resizing a Bean
To resize a bean, select the Bean and position the mouse in a corner of
the boundary for the bean (the mouse pointer changes to a diagonal
arrow pointing into an angle ). Then press SELECT while you
stretch the bean.

Figure 2-3 Resizing a Bean

Note – Not all Beans can be resized.

The BeanBox 2-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Manipulating a Bean

Selecting, Moving, and Resizing Beans

Demonstration - In this demonstration, you will become familiar with


selecting, moving, and resizing beans in the BeanBox.

Assuming you have a jellyBean, juggler, and two ExplicitButton beans


on your BeanBox window, do the following:

1. Move the juggler bean to the bottom of the BeanBox window.

2. Move the two buttons to the top of the BeanBox window (side by
side) and resize them to be 1.5 inches wide and 1 inch in height.

3. Place the jellyBean bean in the center of the BeanBox.


✓ If students have trouble with moving and resizing (because the mouse pointer does not
change to the correct indicator), have them remove the juggler bean until they have
moved and resized everything else. Then place the juggler bean back onto the BeanBox
window. The juggler is CPU intensive, which can interfere with trying to do a resize or
move.

✓ To remove a bean from the BeanBox window, select the bean and choose Edit ➤ Cut.

2-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Notes

The BeanBox 2-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Changing Bean Properties – PropertySheet Window

As noted earlier, when you select a bean in the BeanBox window, the
properties of the bean are displayed in the PropertySheet window.
This enables you to change and customize the bean. For example,
change the foreground or background color, change the font type or
size, and so forth.

Mechanics
The mechanics of changing a property vary according to the property
type. Some properties provide a menu of choices, some are an editable
text field, while still others display a dialog window of choices.
✓ Here are some questions to stimulate thinking ahead to the module on introspection: How
are the properties of a bean discovered? How is the functionality for the type of changes
allowed for each property defined? The answers to these questions are provided later in
this course during the discussions on introspection, properties, property editors, and
customization.

2-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Changing Bean Properties – PropertySheet Window

Effects on the BeanBox Window


When you change a property in the PropertySheet window, a
repainted instance of the bean is displayed in the BeanBox window.
✓ Here is the piece of code from PropertySheet.java:

// Make sure the target bean gets repainted.

if (Beans.isInstanceOf(target, Component.class)) {
((Component)(Beans.getInstanceOf(target, Component.class))).repaint();
}

The BeanBox 2-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Changing Bean Properties – PropertySheet Window

Bean Properties in the PropertySheet Window

Demonstration - This demonstration leads you through changing the


values of bean properties in the BeanBox.

Assuming you have the beans in the BeanBox from the previous
demonstration, do the following:

1. Change the label of the first button bean to “Stop,” its


background color to red, and its font size to 36.

2. Change the label of the second button bean to “Start,” its


background color to green, and its font to TimesRoman, italics,
36.

3. Change the animation rate of the juggler bean to 300.

4. Change the background color of the BeanBox to white.

Figure 2-4 The BeanBox After Property Changes

5. Save the contents of the BeanBox by choosing File ➤ Save.

In the Save File window displayed, type properties.lab.jar


in the File Name field and click on OK.

2-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Changing Bean Properties – Customizers

Some beans have a Customizer class associated with them. This


enables the bean to be customized further than the choices shown in
the PropertySheet window.

Note – Customizer classes are covered later in Module 7,


‘‘Customization.”

The BeanBox 2-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Changing Bean Properties – Customizers

For beans with a customizer, an entry (Customize) is added to the Edit


menu for the bean.

Figure 2-5 Customize Option on the Edit Menu

Choosing Edit ➤ Customize displays a dialog window for further


customization of the bean. The dialog window choices depend on the
customizer associated with the bean. Figure 2-6 on page 21 shows
examples of customizers for two of the demo beans provided with the
BDK.

2-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Changing Bean Properties – Customizers

JDBC SELECT
customizer

ExplicitButton
customizer

Figure 2-6 Examples of Dialog Windows for Bean Customizers

The BeanBox 2-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Bound Properties

Notice that the menu displayed in Figure 2-5 on page 20 also shows a
Bind property choice. If a bean has a bound property (considered a
source), you can connect the bound property to another property, the
target property, on some other bean. When this is done, then the target
property is updated when the bound property is changed.

Note – More details on bound properties and how to create them can
be found in Module 4, ‘‘Bean Properties.”

2-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Bound Properties

Connecting a Bound Property to a Target Property

Demonstration - This demonstration leads you through connecting a


bound property of a bean to a target property of another bean.

1. Clear the BeanBox window (choose File ➤ Clear).

2. Place an ExplicitButton bean onto the BeanBox window.

3. Change the label of the button to ExplicitButton and the color of


the button to light pink (255, 200, 200).

4. With the button selected, choose Edit ➤ Bind property. (Refer to


Figure 2-5 on page 20.)

5. In the displayed dialog window, choose foreground and click on


OK.

Figure 2-7 Property Dialog Window for the Source bean With a
Bound Property

The BeanBox 2-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Bound Properties

6. A rubberband line is displayed. You use this line to stretch and


click on a target bean. In this case, the only other bean is the
BeanBox. So just click anywhere in the BeanBox (except on the
button).

Figure 2-8 Selecting the Target Bean for the Bound Property

Note – The visual style used in the BeanBox for connecting a bound
property to a target property (and for connecting an event from a
source bean to a method in a target bean as you will see on page 26) is
not part of the JavaBeans architecture. Other builder tools may provide
a different interface.

2-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Bound Properties

7. In the dialog window displayed for the selected target (the


BeanBox), choose background and click on OK.

Figure 2-9 Select Target Property to Bind to

8. Change the foreground color of the button and notice that the
background color of the BeanBox also changes.

The BeanBox 2-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Connecting Beans With Event Handlers

To have the events fired by one bean cause another bean to take some
action, you need to connect (or hook up) the beans. Hooking up two
beans involves the following steps:

1. Select a source bean.

Select a bean that generates an event as a result of some user


action. For example, when a user clicks a button, an
ActionEvent is generated.

2. Select an event of the source bean by choosing from those


displayed on the Edit ➤ Events submenu.

Each bean will have its own submenu of events. The events are
grouped, and the groups are named by their event listener
interface. For example, a button is the source for ActionEvent
events (which are associated with the ActionListener
interface), so a button will have an action submenu.

2-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Connecting Beans With Event Handlers

After you choose an event, a rubberband line appears (as it did


when working with a bound property for a bean). Stretch the
rubberband line to a target bean.

3. Select (click on) a target bean.

Events will be sent from the source bean to the target bean.
✓ The BeanBox code will create an adapter class for the source and target to be hooked
together. This code is stored in the beanbox/tmp/sun/beanbox directory.

When you have selected a target bean, an EventTargetDialog


window is displayed.

4. Select a method from the EventTargetDialog window to be called


when the event is fired by the source bean.

The dialog window displays methods of the target bean that


accept the same type event object argument as the one fired by
the event you selected in the source bean.
✓ When you have selected a method in the dialog box, the message Generating and
compiling adapter class is displayed in the EventTargetDialog window. The code that is
generated is fairly simple. A uniquely named hookup class is created that implements the
correct listener interface for the event being fired by the source bean. The handler method
specified by that listener interface is defined. The definition of this handler method calls
the method you chose in the target bean.

The BeanBox 2-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Connecting Beans With Event Handlers

Connecting Beans Through Events


Demonstration - This demonstration leads you through connecting
beans together in the BeanBox.

Restoring the BeanBox

1. Clear the BeanBox window.

2. Restore the BeanBox from the properties.lab.jar file.

a. Choose File ➤ Load.

Note – The Load option is for loading a file that you had previously
saved using File ➤ Save into the BeanBox. The Loadjar option is for
loading a specific JAR file created from a makefile, such as the JAR
files found in the jars directory of the BDK.

✓ Notice that when you reload the properties.lab.jar file, the background of the BeanBox
window remains the same color as it was before the load (regardless of the color of the
background of the BeanBox when the BeanBox was saved to properties.lab.jar). Why?
I am not sure. This happens whether you are in design mode or not.

✓ Note – I have noticed that when in design mode (the View menu), the situation sometimes
occurs that the BeanBox is cleared and the BeanBox itself is not selected. When this
happens, the Load File dialog window does not display when you choose File ➤ Load. To
solve this problem, click on the BeanBox window to select the BeanBox. Then do
File ➤ Load again.

2-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Connecting Beans With Event Handlers

Connecting Beans Through Events

Restoring the BeanBox (Continued)

b. Select properties.lab.jar from the Files list and click


on OK.

Stop Juggling

1. Select the Stop button.

2. Choose Edit ➤ Events ➤ action ➤ actionPerformed.

3. Use the rubberband and click on the juggler bean.

4. Choose stopJuggling from the EventTargetDialog window.

The BeanBox 2-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Connecting Beans With Event Handlers

Connecting Beans Through Events

Start Juggling

1. Select the Start button.

2. Choose Edit ➤ Events ➤ action ➤ actionPerformed.

3. Use the rubberband and click on the juggler bean.

4. Choose startJuggling from the EventTarget Dialog window.

Test the Behavior

Start and stop the juggling by clicking on the appropriate button.

Show and Hide the jellyBean

1. Add two buttons to the BeanBox window, labeled Show and


Hide, respectively.

2. Connect the buttons to the jellyBean bean so that the jellyBean


bean disappears when Hide is clicked and reappears when Show
is clicked.

2-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Saving and Restoring the BeanBox

You can save what you have created in the BeanBox by using
File ➤ Save. A dialog window is displayed for you to specify a file
name to save to.

All the beans in the BeanBox window are written to a serialized stream
(called ___comp_ROOT.ser), and then to a manifest file. The ser file
and all of the hookup classes (that were generated from the beans you
hooked together using events) are written to a JAR file. The name of
the JAR file is the file name you enter in the dialog window.
✓ The ser file created is located in beanbox/tmp. So each time a save is done in the
BeanBox window, this file is rewritten. Serialization is covered in Module 6, ‘‘Persistence.”
Hooking beans up manually to run outside the BeanBox is covered in Module 10, ‘‘Beans
Outside of the BeanBox.”

The BeanBox 2-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Saving and Restoring the BeanBox

Saving and Restoring the BeanBox

Demonstration - You have already saved and restored the BeanBox


window in previous modules. In this demonstration, you will save
and restore the event hookups you made previously.

1. Save your BeanBox to a file called BeanBox.events.jar.

2. Clear the BeanBox.

3. Restore the BeanBox by loading the BeanBox.events.jar file.

4. Make sure the Start, Stop, Hide, and Show buttons function as
expected.
✓ If students saved the state of the BeanBox with the juggler not juggling, when the bean is
restored from the saved file, the juggler is juggling. Why? If you read through the code for
the Load() method in BeanBox.java, it calls readContents(ois) to read back the contents
of the JAR file. In the readContents() method, it checks if the bean is an applet (which the
juggler is), and if so, calls ((Applet)bean).start(); The start() method in the juggler
calls startJuggling(), so the applet begins juggling after being restored.

2-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Adding Your Own Bean to the ToolBox Window

In order to add a bean that you have written (or acquired from the
Internet or a third-party) to the ToolBox window for testing, you need
to create a JAR file.

JAR Files
JAR stands for Java ARchive and is a file format based on the ZIP file
format. It was created for the main purpose of enabling Java applets
and related components (.class files, images, sounds) to be
downloaded to a browser in a single hypertext transfer protocol
(HTTP) transaction. However, a JAR file can contain files of any type.
In beans development, JAR files usually contain a manifest file, may
contain serialized beans (stored in .ser files), and always contain Java
class files.

The BeanBox 2-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Adding Your Own Bean to the ToolBox Window

JAR Files (Continued)


For the BDK 1.X, the JAR files containing beans should contain a
META-INF/MANIFEST.MF manifest file giving the name of each bean
class and specifying that it is a bean. For example, the manifest file for
juggler.jar is initialized as:
Name: sunw/demo/juggler/Juggler.class
Java-Bean: True

See the manifest file specification for more information on manifest


files (http://java.sun.com/beans/related).

One of the added benefits of using the JAR format is that it supports
compression (reducing the size of the downloaded file and
consequently the download time). Moreover, entries in a JAR file can
have digital signatures for authentication and security.
✓ The JAR format is written in the Java programming language and therefore provides a
format that is cross-platform. (The ZIP and tar formats are available for almost every
platform because these formats have been ported to a wide variety of platforms.) The JAR
format is the preferred way to bundle the pieces of a Java applet and to distribute beans.

2-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Adding Your Own Bean to the ToolBox Window

Specifying a JAR File in an HTML File


✓ The HotJava browser 1.0, Netscape Communicator 4.0, and Internet Explorer 4.0 support
JAR files.

To use a JAR file in an HTML file, specify the JAR file using the
archive parameter of the applet tag:
<applet code=Animator.class
archive="jars/animator.jar"
width=460 height=160
>
</applet>

The JAR file must be relative to the location of the hypertext transfer
markup language (HTML) file or the CODEBASE parameter, if used.

Creating JAR Files


JAR files are created using the jar tool which is included with the
JDK. The jar tool can create, extract, or list the contents of a JAR file.
The syntax for the jar tool is:
jar [ctxvfm] [jar-file] [manifest-file] files ...
Option flags are:
ccreate new archive
tlist table of contents for archive
xextract named (or all) files from archive
vgenerate verbose output on standard error
fspecify JAR file name
minclude manifest information from specified
manifest file
If any file is a directory then it is processed
recursively.

The command jar cough fred.jar manifest.tmp *.class


would create a new JAR file called fred.jar, containing the given set
of .class files and a manifest file initialized from manifest.tmp.

The BeanBox 2-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2

Adding Your Own Bean to the ToolBox Window

Using JAM
An easy way to create a JAR file is to create a makefile to use with JAM
(Just Another Make). The online version of the examples provided in
this course can be compiled using the provided JAM makefiles. JAM is
freely available and can be downloaded from
http://www.perforce.com/jam/jam.html.
✓ If a JAR file does not contain a MANIFEST, all entries in the JAR file are considered to be
beans.

✓ The jam utility was chosen for use in this course because it is a cross-platform makefile
utility and freely available on the web.

To create a makefile for your beans, copy the Jamfile and


manifest.tmp templates provided in the course files directory to your
source directory. Edit the Jamfile file and change the entries in the file
to reflect the information of your source code. Then edit the
manifest.tmp file to indicate which of your class files are beans. The
template files are listed in Appendix B.

2-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Adding Your Own Bean to the ToolBox Window

Sample Jamfile Makefile for JAM


Below is a listing of the Jamfile file that is processed automatically by
invoking the jam utility in a compile directory. It illustrates the typical
contents of a makefile that is used to create a JAR file. If the Jamfile
template is used to generate a new makefile, the lines that require
customization are 2, 6, and 11-14. In most cases, you will not need to
change or add any additional information to the template file provided
with the course files.
1 # set the name of the JAR file
2 jar = twoSimple.jar ;
3
4 # this sets the package name of the java files - this is used
5 # to check dependencies of all compiled classes
6 SetPackage sl291 twoSimpleBeans ;
7
8 # list of java sources - if the files are in the package
9 # directory then set the global variable
10 # $(USE_FULL_PATH_FOR_SOURCE) to "TRUE"
11 classes = MyText.java
12 MyButton.java
13 LabelEvent.java
14 LabelListener.java ;
15 DEPENDS all : $(jar) ;
16
17 # add the package of the java files to the list of directories
18 # added to the JAR file
19 AddPackageToJar $(CURR_PACKAGE) ;
20
21 # set the manifest file name - manifest.tmp is normally used
22 SetManifest manifest.tmp ;
23
24 # build the JAR file
25 JarFile $(jar) : $(classes) ;
26
27 # copy the new jar file to the BDK jars directory
28 File $(BDK_JARS_DIR)$(SLASH)$(jar) : $(jar) ;
✓ The jam command is provided in the bin directory of the distribution files.

The BeanBox 2-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Home Directory Structure

The directory structure shown in Figure 2-10 should closely resemble


that of your SL291files directory.
• If necessary, indicate to the students how their directory structure may differ from that
shown here.
SL291files

work BDK bin


02-beanbox ... 10-outsideBB

and so on
JamfilesSource files course_examples solutions

get_started
jars demo beanbox

sunw
run command

and so on

Figure 2-10 SL291files Directory Structure

Everything shown under BDK is provided with the software in the


BDK, except for some of the files in the jars directory. This directory
will be supplemented with JAR files that you create from your
makefiles in the exercises.

All directories named modx-something have been created for this course
and contain course examples used in the Student’s Guide and
solutions for the lab exercises. The packages directory will contain
Jamfiles that you run to compile the exercises. The work subdirectory
will contain the Java source files that you create in the exercises.

2-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Exercise: Adding Your Own Bean to the ToolBox Window

Tasks

Loading Your Own Beans in the BeanBox

Demonstration - In this demonstration, you will generate a JAR file


from a Jamfile makefile and load the JAR files into the BeanBox. You
can then test the beans included in the JAR files.

1. Change to the $HOME/SL291files/work directory.

2. Using the SL291files/Jamfile.template file as a template for


your Jamfile, create an appropriate makefile called choice.jam
for the Java source file MyChoice.java located in the
SL291files/work directory. This Java source file defines a bean
called MyChoice.

a. Set the jar target to choice.jar.

b. Invoke SetPackage rule with sl291 choice. (Do not


forget the space between the package components. This sets
the package to store MyChoice.class.)

c. Set the classes target to MyChoice.java.

d. Invoke the SetManifest rule with choice_manifest.tmp.


(This file is provided for you in the directory.)

3. Invoke jam on your makefile.


% jam -sjf=choice.jam

There are many jam files in the work directory. The -s flag sets a
variable value that is passed to the jam program. When jam is
invoked, it automatically processes the Jamfile. The Jamfile in
the work directory processes the file specified by the jf variable,
if no value is specified, the Jamfile will compile every makefile
in the work directory.

The BeanBox 2-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Adding Your Own Bean to the ToolBox Window

Tasks

Loading Your Own Beans in the BeanBox (Continued)

4. Generate the JAR file twoSimple.jar by typing

% jam -sjf=twoSimple.jam

5. Load your beans in the BeanBox.

▼ If the BeanBox is running on your system, use File ➤ Loadjar


to load jars/choice.jar and jars/twoSimple.jar.

Note – Make sure you are in design mode so that you can see the bean
added to the ToolBox window.

or

▼ If the BeanBox is not running, restart the BeanBox.

6. Test your beans.

Note – The details of why the following beans used can be connected
together and how this all works is presented in Module 3, the bean
event model.

a. Create an instance of MyChoice, MyText, and MyButton


beans on the BeanBox window.

b. Connect the MyButton and MyText beans to the MyChoice


bean using Edit ➤ Events ➤ action ➤ actionPerformed.

c. Choose the addRemoveItem method in the


EventTargetDialog window in both cases (when connecting
the MyText and MyButton beans to the MyChoice bean).

d. Remove choice items by clicking on the MyButton bean.

e. Add choice items by entering a string in the TextField and


pressing Return.

2-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Experiment and Investigate

Demonstration - Take as much time as the instructor allows to


experiment with the BeanBox. Try connecting different beans together
to achieve different behaviors. Try disabling the design mode.
Investigate the following:

● What events does each bean display on the Edit ➤ Events menu?

● Which beans have a customizer?

● Which beans have a bound property?

● What types of properties does each bean display in the


PropertySheet window?

The BeanBox 2-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
BeanBox Summary

Discussion – Take a few minutes to discuss what experiences, issues,


or discoveries you had working in the BeanBox.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the demonstrations.

● Experiences
✓ Ask students what their overall experiences with the BeanBox have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of the demonstrations in
this module.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of these demonstration
experiences.

2-42 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish or answer the following:

❑ What is the purpose of the BeanBox?

❑ Move and resize beans on the Composition window of the


BeanBox.

❑ Change bean properties using the PropertySheet window of the


BeanBox.

❑ Register a bean as the listener of an event generated by another


bean in the Composition window.

❑ Save and restore the current state of the BeanBox.

❑ What is a JAR file and how can it be used?

❑ Create a JAR file for a prewritten bean and add it to the ToolBox
window of the BeanBox.

The BeanBox 2-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
2
Think Beyond

How does the event handling work for beans? How do you define
your own events? How do you indicate you want to receive a
particular event?

2-44 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
The Bean Event Model 3

Course Map
The JDK 1.1 event model was designed to accommodate the JavaBeans
architecture. So to understand how events and event handling works
in the JavaBeans component model, it is necessary to understand
events, listeners, and sources under JDK 1.1.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

3-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Relevance

Discussion – The answers to the following questions are relevant to


the discussion of the Bean event model presented in this module.

1. Can you develop Bean components without understanding how


event handling is done in the JavaBeans component model?

✓ Yes, you can develop a Bean component that is not a source of any events. For example,
a simple graphic of a circle whose size and color can be changed through property
methods would not require you to understand event handling. However, if you intend to
write more complex Beans that are meant to be connected to other Beans in meaningful
ways, you must understand the event model.

2. Can you build an application or applet in a builder tool without


understanding the event model?
✓ Although it is possible to build an application or applet in a builder tool without
understanding the event model, you will not be able to figure out what is wrong if things
do not work the way you intended. A firm grasp of the event model is necessary if you are
building real-world type applications or applets. Things usually do not work the way you
intend the first time around.

3-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Objectives

✓ Although this module spends time illustrating how to create new events, listener
interfaces, and sources, you should mention to students that they should try to use those
provided by the JDK whenever possible (for greater reusability). The intent here is to have
students completely understand all aspects of the delegation event model.

Upon completion of this module, you will be able to:

● Define event, event source, and event listener.

● Distinguish between multicast and unicast sources.

● Create a multicast or unicast source.

● Implement a specified listener interface.

● Create two simple Bean components in which one is a listener for


the events of the other.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans API 1.0 Specification. [Online]. Available:


http://splash.javasoft.com/beans/spec.html

● Java AWT: Delegation Event Model. [Online]. Available:


http://www.javasoft.com:80/products/jdk/1.1/docs/
guide/awt/designspec/events.html
✓ In the first several months after this course is released, you might have students in the
class who are unfamiliar with the new JDK 1.1 event model. So, although SL-275: Java
Application Programming are prerequisites for this course, students might be familiar with
only the JDK 1.0.2 event model.

✓ As more students progress through SL-275 and the new event model, you may find that
much of the material in this module can be covered quickly as review.

The Bean Event Model 3-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

What Is an Event?

An event is asynchronous data generated by the window server and


results from some device activity. The devices are usually a mouse and
keyboard. Examples of events include:
✓ This is not an all-inclusive list.

● Window events – Destroying, exposing, iconifying, de-iconifying,


and moving windows.

● Mouse events – Moving the mouse, dragging the mouse, having


the mouse enter or exit a component, pressing a mouse button,
and releasing a mouse button.

● Keyboard events – Pressing a key, or releasing a key.

● List events – Selecting or deselecting a list item.

● Scrolling events – Scrolling a line up or down, a page up or down,


or scrolling to an exact location.

3-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
What Is an Event?

When the user performs an action at the user interface, this causes an
event to be issued. In the Java programming language, events are
objects that describe what happened. A number of different types of
event classes exist to describe various general categories of user action.

The Bean Event Model 3-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Delegation Model Overview

The event model in JDK 1.1 and the event model used by the
JavaBeans architecture is a delegation model. This model is composed
of three main parts: sources, events, and listeners.

Sources and Listeners


A source of an event is an object that originates or fires the event. A
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 it wants to receive (be notified of)


events of a particular type. Listeners register for events using the
methods defined by the source of those events.
✓ More details on defining sources, registering listeners, and handling events is provided
later in this module.

3-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Delegation Model Overview

Propagating Notification of Events


Notification of events is propagated from the source to the listener
using a method call on the listener (Figure 3-1).

Register listener

Event source Event Event listener


Fire
event

Figure 3-1 Delegation Event Model

The Bean Event Model 3-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Simple Code Example

Suppose you have an application that performs some action when a


button is clicked. Button components are defined as sources of an
event type called ActionEvent and listeners of ActionEvent events,
register for these events using the addActionListener() method.
1 public class ButtonHandler implements ActionListener {
2 /**
3 * Component that will contain messages about events generated.
4 */
5 TextArea output;
6
7 /**
8 * Creates an ActionListener that will put messages in TextArea
9 * everytime event received.
10 */
11 public ButtonHandler(TextArea c) { output = c; }
12
13 /**
14 * When receives action event notification, appends message to the
15 * TextArea passed into the constructor.
16 */
17 public void actionPerformed(ActionEvent e) {
18 output.appendText("Action occurred:" + e + "\n");
19 }
20 }
21
22 class ActionTester {
23 public static void main(String args[]) {
24 Frame f = new Frame("Button Handler");
25 TextArea area = new TextArea(6, 80);
26 Button button = new Button("Fire Event");
27
28 button.addActionListener(new ButtonHandler(area));
29 f.add(button, BorderLayout.NORTH);
30 f.add(area, BorderLayout.CENTER);
31 f.pack();
32 f.setVisible(true);
33 }
34 }
✓ All of the code samples shown in this module are included in the course_examples
directory for this module.

3-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Simple Code Example


✓ Students might ask you what you do in an application that has several buttons, some text
fields, and so on that all fire ActionEvent events. What do you do if an object is registered
with each of these sources? How do you determine which component the event originated
from when you have just one actionPerformed method? This issue is addressed in Module
8, ‘‘Event Adapters.”

✓ Rather than using an adapter, you could create a different action listener, one for each
distinct purpose and registered with just one source that fires an ActionEvent.

Code Explanation
There are several key items to point out in the code example:

● A ButtonHandler is registered as a listener of the ActionEvent


fired by the button using addActionListener(). This method
requires as an argument an object that implements the
ActionListener interface. This is why the ButtonHandler class
is defined as:
public class ButtonHandler implements ActionListener {
● The ActionListener interface (which the ButtonHandler
implemented) requires that you define an actionPerformed()
method. This is the method that is called when the button is
clicked. It must be defined as:
public void actionPerformed(ActionEvent ev)
The Bean Event Model 3-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Categories of Events

For each category of events, there is an interface that must be defined by any class that
wants to receive the events. That interface specifies one or more methods that must be
defined. Those methods will be called when particular events arise. Table 3–1 lists the event
categories, giving the interface name for each category and the methods required. The
method names are mnemonic, indicating the conditions that will cause the method to be
called.

Table 3-1 Categories of Events and Listener Interfaces

AWT Component That


Category Interface Name Methods
Fires Event
Action ActionListener actionPerformed(ActionEvent) Button, TextField (when Return is
pressed), MenuItem, List (when an
item is double-clicked)

Item ItemListener itemStateChanged(ItemEvent) Checkbox, CheckboxMenuItem,


Choice

Mouse Motion MouseMotionListener mouseDragged(MouseEvent) Canvas, Panel, Frame, Dialog,


mouseMoved(MouseEvent) Window, Component

Mouse Button MouseListener mousePressed(MouseEvent) Canvas, Panel, Frame, Dialog,


mouseReleased(MouseEvent) Window, Component
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)

Key KeyListener keyPressed(KeyEvent) Component


keyReleased(KeyEvent)
keyTyped(KeyEvent)

Focus FocusListener focusGained(FocusEvent) Component


focusLost(FocusEvent)

Adjustment AdjustmentListener adjustmentValueChanged(AdjustmentEvent) Scrollbar

3-10 Course Title


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1998
3
Table 3-1 Categories of Events and Listener Interfaces (Continued)

AWT Component That


Category Interface Name Methods
Fires Event
Component ComponentListener componentMoved(ComponentEvent) Dialog, Frame
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)

Window WindowListener windowClosing(WindowEvent) Dialog, Frame


windowOpened(WindowEvent)
windowDeiconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)

Container ContainerListener componentAdded(ContainerEvent) Container


componentRemoved(ContainerEvent)

Text TextListener textValueChanged(TextEvent) TextComponent

The event argument shown for each method indicates the event type that is handled by the listener.

The Component class is also a source of ComponentEvent events.

Course Title 3-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1998
3

Obtaining Details About the Event

When handler methods are called, they receive an event state object
that contains all of the relevant information about the event. The
attributes associated with the event are accessed through the object’s
methods. All event classes derive from java.util.EventObject. The
most useful method in the EventObject class is:
public Object getSource()

This method returns the object that generated the event. Notice the
source object does not have to be a subclass of java.awt.Component.
The event model in JDK is most often applied to GUI components, but
it can just as easily be applied to a non-visual timer, file transfer
protocol (FTP) client, or database query object.

To determine the details of what information is available for each


category of event, check the appropriate class documentation for the
event class. Do not forget to look at the API of all of the parent classes
in addition to the class of the object being handled.
✓ For example, for a MouseEvent, there is information about the number of mouse clicks
associated with the event (use getClickCount() to retrieve), in addition to the x and y
coordinates.

3-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Creating Your Own Event

Although the JDK defines many types of events, there may come a
time when an appropriate event class does not exist. In these cases,
create a new event class by subclassing either java.util
EventObject or one of its subclasses.

For example, suppose you want to create an event that signifies the
change of a stock price. You could define an event called
StockPriceChangeEvent. The definition of the event could be:
1 import java.util.*;
2 public class StockPriceChangeEvent extends EventObject {
3 private Stock stock;
4
5 public StockPriceChangeEvent(Object source, Stock s) {
6 super(source);
7 stock = s;
8 }
9 public Stock getStock() {
10 return stock;
11 }
12 }

The Bean Event Model 3-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Creating Your Own Event

✓ Point out to students that the Stock is not derived from Component and it acts as the
source of the event.

The event handler for this event can use event.getStock() to


determine the stock that changed value, and then use the stock to
determine the stock’s symbol, price, price to earnings ratio (PE), or
other applicable information. The Stock class is not shown in the code
listings.
✓ Point out to students that you should not arbitrarily define your own events, but reuse the
existing ones as much as possible (at least by subclassing).

3-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Listeners

Event Listeners
Every event class is matched to one or more event listener interfaces.
For example, ActionListener handles ActionEvent, FocusListener
handles FocusEvent, and KeyListener handles KeyEvent. Some
event types are supported by multiple-event listener interfaces. For
example, MouseEvent is supported by MouseListener and
MouseMotionListener interfaces.

A class capable of generating an event type provides registration


methods for listeners to become part of the distribution list for a
certain type of event. These methods have the form
addXXXListener(XXXListener al) and
removeXXXListener(XXXListener rl). For example, the Button
class defines addActionListener(ActionListener al) and
removeActionListener(ActionListener rl) methods.

The Bean Event Model 3-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Listeners

ActionListener Interface
Event listener interfaces are always defined with EventListener as
one of the base interfaces. The ActionListener interface of the JDK is
defined in the ActionListener.java file. Its contents are shown
below:
1 package java.awt.event;
2 import java.util.EventListener;
3
4 /**
5 * The listener interface for receiving action events.
6 */
7 public interface ActionListener extends EventListener {
8 /**
9 * Invoked when an action occurs.
10 */
11 public void actionPerformed(ActionEvent e);
12 }

3-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Listeners

Creating Your Own Listener Interface


To create your own listener interface, give it a name, extend
EventListener, and specify the method(s) called when the event is
generated. For example, a suitable event listener for the
StockPriceChangeEvent would be:
1 import java.util.EventListener;
2
3 public interface StockPriceChangeListener extends EventListener {
4 public void priceChange(StockPriceChangeEvent e);
5 }

Once the event and the listener interface are defined, you need to
define a source that generates the StockPriceChangeEvent and
indicates how listeners are to register to receive the event.
✓ Try to use the standard interfaces whenever possible.

The Bean Event Model 3-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Event Sources

Using Common Sources Provided by the AWT Package


All AWT components (buttons, text fields, checkboxes, choices, and so
on) have been defined in the JDK as sources of specific events (refer to
Table 3-1 on page 10). You can create simple Beans by extending any of
these components. You need not define listener interfaces or events,
this is already done for you in the JDK.

Creating Your Own Source


If you have created your own event type and listener interface, you
need to define a source that will fire your event.

3-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Event Sources

Identifying Sources
A source for a type X event identifies itself by defining the registration
methods that a listener is required to use in order to receive
notification of type X events. These registration methods include an
addXXXListener(XXXListener al) and a
removeXXXListener(XXXListener rl) method.

Event sources can identify themselves as multicast or unicast. A


multicast source allows multiple listeners to register for the events it
fires. A unicast source allows only one listener to be registered at any
time. All current AWT components are multicast sources.

The Bean Event Model 3-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Event Sources

Multicast Syntax
A multicast source can have multiple listeners at any time.

The syntax for creating a multicast source (the typical case) is to define
the add and remove methods for the listener type:
1 private Vector listeners = new Vector();
2
3 public void addStockPriceChangeListener(StockPriceChangeListener spl)
{
4 listeners.addElement(spl);
5 }
6
7 public void
8 removeStockPriceChangeListener(StockPriceChangeListener spl) {
9 listeners.removeElement(spl);
10 }

These methods enable other objects to be added or removed as


listeners for an event type such as ActionEvent or
StockPriceChangeEvent.

3-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Event Sources

Unicast Syntax
If you have a situation that warrants only one listener at any time (the
source is unicast), the syntax is similar to the multicast case. The only
difference is that the add method needs to throw a
TooManyListenersException if there is already a listener registered.
1 private StockPriceChangeListener listener = null;
2
3 public void addStockPriceChangeListener(StockPriceChangeListener spl)
4 throwsjava.util.TooManyListenersException
5 {
6 if (listener == null) {
7 listener = spl;
8 } else {
9 throw new java.util.TooManyListenersException();
10 }
11 }
12
13 public void removeStockPriceChangeListener
14 (StockPriceChangeListener spl) {
15 if (listener == spl) {
16 listener = null;
17 }
18 }

The Bean Event Model 3-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Event Sources

Notifying All Listeners of an Event


When your source generates your event type, it must also notify all
listeners of the event so that they can handle the event with the
method required by the listener interface (which they implement). The
following helper method would appear in a class to generate the event
notification:
1 protected void notifyStockEvent(Stock stock) {
2 // Generate your event
3 Vector lis;
4 StockPriceChangeEvent e;
5 e = new StockPriceChangeEvent(this, stock);
6 lis = (Vector) listeners.clone();
7
8 // Fire the event to every listener
9 StockPriceChangeListener spcl;
10 for (int i = 0, len=lis.size(); i < len; i++) {
11 spcl = (StockPriceChangeListener)lis.elementAt(i);
12 spcl.priceChange(e);
13 }
14 }

Note – Complete code for the Stock example can be found in the
course_examples directory for this module.

✓ The JavaBeans specification recommends that you copy the listener vector in order to
freeze the state of the set of EventListeners that the event should be delivered to prior to
delivery. This ensures that any changes made to the vector from a target listener’s method
during the delivery of this event will not take effect until after the event is delivered.

3-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Event Delivery Issues

Synchronous Delivery
Most event sources are multicast, in which case the source is
responsible for keeping track of all of the listeners for each different
event type it fires. When an event occurs, the source must call each
target listener for that event. This event delivery is synchronous; the
call to a target listener is a normal Java method invocation, executed
synchronously, using the caller’s thread.
✓ It is important, therefore, that event handler methods do not take an excessively long time
to complete as that would reduce the perceived responsiveness of the overall system.
Time-consuming processing, such as querying a database, should be delegated to
separate threads.

The Bean Event Model 3-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Event Delivery Issues

Multiple Listeners
If you want to write a program that performs multiple actions based
on a single event, you should code that behavior into your handler
method. However, sometimes a program’s design requires multiple
unrelated parts of the same program to react to the same event. This
might happen if, for example, a context-sensitive help system is being
added to an existing program.

The listener mechanism allows you to call an addXXXListener


method as many times as needed, specifying as many different
listeners as your design requires. All registered listeners will have their
handler methods called when the event occurs.

Note – The order in which the handler methods is called is undefined.


Generally, if the order of invocation matters, then the handlers are not
unrelated, and you should not use this facility to call them. Instead,
register only the first listener, and have that one call the others directly.

✓ There are issues with how delivery of events is handled by the source if a target listener
throws an exception (which they are allowed to do). There are also race and deadlock
situations in a multi-threaded system. See the JavaBeans specification for more details on
these situations.

3-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Recap of Event Model

Figure 3-2 summarizes the main concepts of the delegation event


model.

XXXListener interface
public interface XXXListener extends EventListener{
XXXHandler(XXXEvent evt);
}

XXXEvent
public class XXXEvent extends EventObject{
//Definition for XXXEvents
}

Event source
Defines listener registration methods:
public void addXXXListener(XXXListener al) and
public void removeXXXListener(XXXListener rl)

Fires XXXEvent

Notifies all listeners of an XXXEvent

Event listener
Implements the XXXListener interface

Defines the public void XXXHandler(XXXEvent evt) method

Adds itself as a listener of XXXEvents using source.addXXXListener()

Figure 3-2 Recap of Event Model

Note – This is the generic delegation event model. Beans do not


usually do addXXXListener. This is usually done by the builder tool
when two Beans are hooked together.

The Bean Event Model 3-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

Bean Components and Event Handling

So what do sources, events, and listeners mean for Bean components?


In the BeanBox, beans are connected through event handling using
Edit ➤ Events. This enables you to test how different Bean
components might be used together in an application or an applet.

Example of Stock Market Beans


The remainder of the module will be devoted to using the
StockPriceChangeEvent and associated listener
StockPriceChangeListener. After providing a simple
implementation of a Stock class, two Beans will be developed to
present the value of a stock being actively traded. The example will
use a class that has already been developed (and is a Bean) called
TimerBean to generate an event after a set period of time. The source
code for the TimerBean is provided in the stock directory.

3-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Bean Components and Event Handling

Example of Stock Market Beans

Stock Class

1 package sl291.stock;
2
3 public class Stock {
4 String company;
5 String symbol;
6 double price;
7
8 public Stock(String co, String sym, double p) {
9 company = co;
10 symbol = sym;
11 price = p;
12 }
13
14 public void setCompany(String co) { company = co; }
15
16 public String getCompany() { return company; }
17
18 public void setSymbol(String sym) { symbol = sym; }
19
20 public String getSymbol() { return symbol; }
21
22 public double getPrice() { return price; }
23
24 public void setPrice(double p) { price = p;}
25 }

The Bean Event Model 3-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
BeanComponents and Event Handling

Example of Stock Market Beans

StockPriceChangeEvent Code

Just in case, here is the source code for the event and listener again:
1 package sl291.stock;
2
3 import java.util.EventObject;
4
5 public class StockPriceChangeEvent extends EventObject {
6 private Stock stock;
7
8 public StockPriceChangeEvent(Object source, Stock s) {
9 super(source);
10 stock = s;
11 }
12
13 public Stock getStock() { return stock; }
14 }

1 package sl291.stock;
2
3 import java.util.EventListener;
4
5 public interface StockPriceChangeListener extends EventListener {
6 public void priceChange(StockPriceChangeEvent e);
7 }

3-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
BeanComponents and Event Handling

Example of Stock Market Beans

StockWatcher Code

The StockWatcher class creates a timer that will generate an


ActionEvent every 5 seconds. Upon receiving the ActionEvent, the
watcher decides whether its stock went up, down, or stayed the same.
If the stock price moves, a StockPriceChangeEvent is generated and
transmitted to every listener.
1 package sl291.stock;
2
3 import java.awt.event.*;
4 import java.util.Vector;
5 import sl291.beans.*;
6
7 public class StockWatcher implements ActionListener {
8 Stock stock;
9 Vector listeners = new Vector();
10
11 public StockWatcher() {
12 this(new Stock("Sun Microsystems", "SUNW", 50));
13 }
14
15 public StockWatcher(Stock s) {
16 stock = s;
17 //create a timer, register, and make timer active.
18 TimerBean t = new TimerBean(5000);
19 t.addActionListener(this);
20 t.setActive(true);
21 }
22
23 public String getCompany() { return stock.getCompany(); }
24
25 public void setCompany(String co) { stock.setCompany(co); }
26
27 public String getSymbol() { return stock.getSymbol(); }
28
29 public void setSymbol(String s) { stock.setSymbol(s); }
30
31 public void setPrice(double p) { stock.setPrice(p); }
32
33 public double getPrice() { return stock.getPrice(); }

The Bean Event Model 3-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Bean Components and Event Handling

Example of Stock Market Beans

StockWatcher Code (Continued)

34 public void actionPerformed(ActionEvent e) {


35 double random = Math.random();
36
37 if (random < .28) {
38 //price went down
39 stock.setPrice(stock.getPrice()-.25);
40 } else if (random > .7) {
41 //price went up
42 stock.setPrice(stock.getPrice()+.25);
43 } else {
44 return;
45 }
46 generateStockEvent();
47 }
48
49 public void
50 addStockPriceChangeListener(StockPriceChangeListener spcl) {
51 listeners.addElement(spcl);
52 }
53
54 public void
55 removeStockPriceChangeListener(StockPriceChangeListener spcl) {
56 listeners.removeElement(spcl);
57 }
58
59 private void generateStockEvent() {
60 StockPriceChangeEvent event;
61 StockPriceChangeListener spcl;
62 event = new StockPriceChangeEvent(this, stock);
63 Vector v = (Vector)listeners.clone();
64
65 for (int i=0, len=v.size(); i<len; i++) {
66 spcl = (StockPriceChangeListener)v.elementAt(i);
67 spcl.priceChange(event);
68 }
69 }
70 }

3-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Bean Components and Event Handling

Example of Stock Market Beans

StockDetail Class

The StockDetail class provides a GUI interface to monitor the


information about a stock. This class implements the
StockPriceChangeListener interface so it will be capable of
receiving the stock price change notifications for the StockWatcher.
1 package sl291.stock;
2
3 import java.awt.TextArea;
4
5 public class StockDetail extends TextArea
6 implements StockPriceChangeListener
7 {
8 public StockDetail() {
9 this(null);
10 }
11
12 public StockDetail(Stock s) {
13 super(4, 30);
14 showDetail(s);
15 }
16
17 public void priceChange(StockPriceChangeEvent e) {
18 showDetail(e.getStock());
19 }
20
21 public void showDetail(Stock s) {
22 if (s == null) {
23 setText("");
24 return;
25 }
26
27 setText("Company: " + s.getCompany() + "\n");
28 appendText(" symbol: " + s.getSymbol() + "\n");
29 appendText(" price: " + s.getPrice());
30 }
31 }

The Bean Event Model 3-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Bean Components and Event Handling

Running Stock Market Beans


After you create a JAR file for these classes and add it to the BeanBox,
you can choose StockWatcher and StockDetail from the ToolBox
window and drop them in the BeanBox window. Change the
properties in the Property Sheet window as you want, then connect
the StockWatcher Bean that fires the StockPriceChangeEvent to the
handler method priceChange() of the StockDetail Bean.

Now, the TextArea of the StockDetail Bean will display the real-time
information about the stock.

3-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Exercise: Working With the Bean Event Model

Exercise objective – The objective of this exercise is to have you create


your own event, define your own listener interface, create a Bean as a
source for the new event, and create a Bean that implements the new
listener interface and defines the handler method required by the
interface.

Preparation
To be prepared to do this exercise, you should understand the
terminology presented in Module 2, ‘‘The BeanBox.” This includes
understanding how Beans are hooked together in the BeanBox and
some familiarity with the Edit ➤ Events submenu. You also should be
able to code what is asked of you in the tasks for this exercise using
the sample code that was presented in this module.

The Bean Event Model 3-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Exercise: Working With the Bean Event Model

Tasks

Creating a New Event and Listener Interface

Note – All of the code that you create here will be part of the
sl291.dataTable and sl291.dataButton packages.

1. Change to the SL291files/work directory.

This directory contains the Java source and class files for the Bean
components and their associated event and listener definitions.
The makefile is already created and is called dataTable.jam.

2. Create a new event called DataTableEvent. This event is created


with two arguments:

▼ A source component

▼ A two-dimensional array of Strings (the table data)

In addition, the event enables access to the data stored in the


table through a method called getData().

3. Create a new listener interface called DataTableListener with


event handler named fireDataTableEvent().

3-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Exercise: Working With the Bean Event Model

Tasks

Creating Beans That Use the New Event and Interface

1. Create a Bean called DataTableBean. Use the template provided


in SL291files/work/DataTableBean.java. The template has
left the class declaration, constructor definition, and
DataTableEvent handler method definition for you to fill in.

This Bean should satisfy the following specifications:

▼ The DataTableBean can be resized at any time based on the


contents of a DataTableEvent event.

▼ The Bean is a Panel component that uses GridLayout and


contains an x by y grid of TextField components of size
cellSize (a fixed size).

▼ Upon receipt of a DataTableEvent, the current table is resized


to the new dimensions and the table populated with the data
from the event.

2. Create a Bean called DataTableButton that extends Button.

This Bean will be used to send test data to the DataTableBean.


When the button is clicked, generate a DataTableEvent event
with a 2x3 string of test data you have defined and notify all
registered listeners of the DataTableEvent event.

The Bean Event Model 3-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Exercise: Working With the Bean Event Model

Tasks

Testing Your Beans in the BeanBox

1. Change to the SL291files/work directory.

2. The makefile for this lab is dataTable.jam. It compiles all of the


files specified in the instructions, creates a JAR file, and copies it
to the jars directory of the BeanBox. Make sure you inspect the
makefile to ensure all of your classes are listed.

Note – The JAR file created for the DataTableButton Bean needs the
related class files for the listener interface and event type.

3. Use the makefile created in step 2 to generate your JAR files for
the DataTableBean and the DataTableButton Beans.

4. Test your Beans by creating an instance of the DataTableBean and


DataTableButton Beans in the BeanBox window and connecting
them using DataTableEvent.

DataTableEvent DataTableBean
DataTableButton
handles DataTableEvents with
fireDataTableEvent

Figure 3-3 Overview of Bean Hookup

3-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Exercise: Working With the Bean Event Model

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

The Bean Event Model 3-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish or answer the following:

❑ Define event, event source, and event listener.

❑ Define the difference between multicast and unicast sources.

❑ Create a multicast or unicast source.

❑ Implement a specified listener interface.

❑ Create two simple Bean components in which one is a listener for


the events of the other.

3-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3
Think Beyond

In working with the BeanBox, different properties were displayed in


the PropertySheet window for each Bean you selected on the
Composition window. How do you create Bean properties? Are there
different types of properties?

The Bean Event Model 3-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
3

3-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Bean Properties 4

Course Map
This module discusses the types of properties defined in the JavaBeans
specification and how to create different bean properties.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

4-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – You are about to learn how to create bean properties.


You might have asked yourself the following questions already:

1. If you acquire bean components from a third-party or from the


Internet, how can you affect the appearance of the beans or their
behavior without the source code? This can be important if you
are building new applications that intend to use these beans.
✓ Bean properties enable developers to “customize” newly acquired beans from various
vendors. The properties are accessed through accessor methods (getXXX and setXXX
methods). A developer can change the values of a bean’s properties in a builder tool to fit
the needs of the application being developed.

2. As a developer of bean components, can all properties or


attributes of your bean be classified as the same? For example,
are the properties all simple? Should the change of a property
affect other beans? Should the change be checked to see if it is
valid? In addition, what method will you use to enable
application builders to change properties of your bean?
✓ As a bean developer, you will need to decide what properties are appropriate, and
necessary, for your bean. You also need to decide if these properties are independent and
irrelevant to other beans that might be used with your beans in an application. Other
decisions include how the end developer will be allowed to change the properties. Will
this be done through a property editor and a property sheet, or will you provide a type of
“wizard” (a customizer) for your bean?

4-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Objectives

Upon completion of this module, you will be able to:

● Define a bean property.

● Compare the different types of bean properties.

● Explain how the naming conventions for get and set methods are
used to locate properties.

● Determine if a property is read-write, read-only, or write-only.

● Create a bean component with a bound property.

● Create a bean component with a constrained property.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

For more details on the topics covered in this module, consult

● JavaBeans API 1.0 Specification. [Online]. Available:


http://splash.javasoft.com/beans/spec.html.
✓ Much insight on properties, property editors, and the PropertySheet window in the
BeanBox and how it and property changes work can be gleaned from reading through the
following source files provided with the BDK:

• apis/sun/beans/editors/*.java – A description of all editors for standard types


provided by JavaBeans (includes BoolEditor.java, ColorEditor.java,
FontEditor.java, StringEditor.java, and so on).
• beanbox/sun/beanbox/PropertySheet.java – Describes how the views that are
used on the PropertySheet window are determined.

• java/beans/PropertyEditorManager.java – Describes how the registry of


property editors works.

Bean Properties 4-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

What Is a Bean Property?

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.

Types of Bean Properties


There are several types of bean properties defined in the JavaBeans
specification:

● Simple – A bean property with a single value whose changes are


independent of changes in any other property.

● Bound – A bean property in which a change to it results in a


notification being sent to some other bean.

Note – Recall how you connected a bound property on one bean to a


target property on another bean in Module 2, ‘‘The BeanBox.”

4-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
What Is a Bean Property?

Types of Bean Properties (Continued)


● Constrained – A bean property in which a change results in
validation by another bean. The other bean may reject the change
if it is not appropriate.

● Indexed – A bean property that supports a range of values instead


of a single value.

Note – The syntax for indexed properties is discussed in Module ,


‘‘Introspection.” Details of this property type are not discussed further
in this course.

Bean Properties 4-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Properties and get/set Methods

All properties of a bean are accessed using method calls on the bean.
These accessor methods follow a naming convention, and except for
Boolean properties, are the getXXX and setXXX methods.

Note – A Boolean property uses isXXX and setXXX methods.

Read and Write Properties


A bean property can be read-only, read-write, or write-only:

● read-only – A bean property XXX is read-only if only a getXXX


method is defined for the bean.

● read-write – A bean property XXX is read-write if getXXX and


setXXX methods are defined for the bean.

● write-only – A bean property XXX is write-only if only a setXXX


method is defined for the bean.
✓ Note that a write-only property might seem a bit strange—you cannot query what the
current value of the property is, but you can set it to a new value.

4-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Properties and get/set Methods

Naming Conventions
The name of a bean property and the names of the property accessor
methods are dependent on each other. So, for example, a bean with a
read-write property called height would imply getHeight() and
setHeight() methods for the bean.

Note – The convention is to capitalize the first letter of the property


name. However, the BeanBox applies decapitalization to get and set
methods when determining the string to display on the PropertySheet
window. Hence, the height property is displayed with the string
“height”.

The significance of adhering to the naming conventions (discussed in


more detail in Module , ‘‘Introspection.”) is that the introspection
process depends on these conventions to discover the properties and
behavior of a bean. Essentially, the introspection process inspects the
class file for the bean and dynamically determines the properties and
events supported by examining the names of every public method. For
example, if the process finds setName() and getName() methods, the
bean will be given a read-write property called name.

Bean Properties 4-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Simple Properties

Defining Simple Properties


Simple properties for beans are created using get and set methods
that adhere to the following syntax:
public PropertyType getPropertyName();
public void setPropertyName(PropertyType a);

For example, a property used in many beans is a foreground property,


which is defined by the following methods:
public Color getForeground() {...}
public void setForeground(Color fc) {...}

4-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Notes

Bean Properties 4-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Simple Properties

Adding Simple Properties to a Bean


To add simple properties to a bean, decide whether each property will
be read-only, read-write, or write-only. Then add the appropriate
getXXX and setXXX methods (or isXXX and setXXX methods for
Boolean properties).

Here is an example of a simple bean which displays a colored circle.


1 package sl291.circle;
2
3 import java.awt.*;
4
5 /** A simple Bean that is a Circle with properties to
6 * change color, change radius, calculate circumference
7 */
8 public class CircleBean extends Canvas {
9 private Color circleColor = Color.blue;
10 private int radius;
11 private double circum;
12

4-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Simple Properties

Adding Simple Properties to a Bean (Continued)


13 //Construct a small circle
14 public CircleBean() {
15 setSize(new Dimension(60,60));
16 this.radius= 100;
17 this.circum = getCircum();
18 }
19
20 public void paint(Graphics g){
21 g.setColor(circleColor);
22 g.fillArc(0,0,radius,radius,0,360);
23 }
24
25 // read-write properties - these show up in BeansBox
26 public Color getColor() {
27 return circleColor;
28 }
29
30 public void setColor(Color newColor) {
31 circleColor = newColor;
32 repaint();
33 }
34
35 public int getRadius() {
36 return radius;
37 }
38
39 public void setRadius(int r) {
40 radius = r;
41 circum = 2 * 3.14159 * radius;
42 System.out.println("Circumference: " + circum);
43 repaint();
44 }
45
46 // read-only property - these do not show up in BeansBox
47 public double getCircum() {
48 return circum;
49 }
50 }

Bean Properties 4-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Simple Properties

Adding Simple Properties to a Bean (Continued)


Figure 4-1 displays the PropertySheet window and Edit menu for the
CircleBean.

Color property

Radius property

Figure 4-1 PropertySheet Window and Edit Menu for the


CircleBean

✓ Other properties are obtained from the Canvas component that the bean inherits.

4-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Bound Properties

Changes to a bound property X result in changes to properties that are


bound to property X.

Defining Bound Properties


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 for
PropertyChangeListeners and fire a PropertyChangeEvent event
to PropertyChangeListeners by calling their propertyChange()
methods.
✓ The PropertyChangeListener interface specifies the method propertyChange with
the PropertyChangeEvent as an argument.

Bean Properties 4-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Bound Properties

PropertyChangeSupport Class
The JavaBeans API provides a utility class called
PropertyChangeSupport that makes creating a bound property easier
for a developer. This class can be used to keep track of
PropertyChangeListeners and to fire the PropertyChangeEvent event
when your bound property changes. This means that you do not have
to maintain the vector of all listeners and call the propertyChange()
method on each listener when your bound property changes.

Below is the typical code you would incorporate into your bean to
handle registration of PropertyChangeListeners for your bound
property.
1 PropertyChangeSupport support = new PropertyChangeSupport(this);
2
3 //registration methods for PropertyChangeListeners
4 public void addPropertyChangeListener(PropertyChangeListener pl) {
5 support.addPropertyChangeListener(pl);
6 }
7
8 public void removePropertyChangeListener
9 (PropertyChangeListener pl) {
10 support.removePropertyChangeListener(pl);
11 }

Modifying the Property set Method


One additional change needs to be made within the definition of your
setXXX method for the bound property. This change is a method call
for firing the PropertyChangeEvent event. The syntax for this call is:
support.firePropertyChange(String PropertyName, Object oldValue,
Object newValue);
✓ Note that the second and third arguments are an Object. This means that for property
types such as int or boolean, you need to use the wrapper classes Integer or
Boolean.

4-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Bound Properties

Example of Creating a Bound Property


Suppose you want to make the color property of the
CircleBean a bound property. Making the changes noted
previously, you would have:
1 package sl291.circle;
2
3 import java.beans.*;
4 import java.awt.*;
5
6 /** A simple Bean that is a Circle with properties to
7 * change color, change radius, calculate circumference
8 */
9
10 public class CircleBean extends Canvas {
11 private Color circleColor = Color.blue;
12 private int radius;
13 private double circum;
14
15 private PropertyChangeSupport support = new
16 PropertyChangeSupport(this);
17
18 //registration methods for PropertyChangeListeners
19 public void addPropertyChangeListener(PropertyChangeListener pl) {
20 support.addPropertyChangeListener(pl);
21 }
22
23 public void removePropertyChangeListener
(PropertyChangeListener pl) {
24 support.removePropertyChangeListener(pl);
25 }

Bean Properties 4-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Bound Properties

Example of Creating a Bound Property (Continued)


26 //Construct a small circle
27 public CircleBean() {
28 setSize(new Dimension(60,60));
29 this.radius= 100;
30 this.circum = getCircum();
31 }
32
33 public void paint(Graphics g){
34 g.setColor(circleColor);
35 g.fillArc(0,0,radius,radius,0,360);
36 }
37
38 //Simple properties
39 public Color getColor() {
40 return circleColor;
41 }
42
43 public void setColor(Color newColor) {
44 Color prevColor = circleColor;
45 circleColor = newColor;
46 support.firePropertyChange("color", prevColor, circleColor);
47 repaint();
48 }
49
50 public int getRadius() {
51 return radius;
52 }
53
54 public void setRadius(int r) {
55 radius = r;
56 circum = 2 * 3.14159 * radius;
57 System.out.println("Circumference: " + circum);
58 repaint();
59 }
60
61 // read-only property
62 public double getCircum() {
63 return circum;
64 }
65 }

4-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Bound Properties

Bound Properties and the BeanBox Edit Menu


The color property of CircleBean can now be bound to a target
property of some other bean (similar to what you did previously with
the BeanBox in Module 2). Notice that the Edit menu for the
CircleBean has changed to indicate a bound property as displayed in
Figure 4-2.

Figure 4-2 Edit Menu and PropertyNameDialog Window for


CircleBean With a Bound Property

Note – The PropertySheet window for CircleBean does not change


even though the color property became a bound property.

✓ It is not shown here but the Edit ➤ Events submenu adds a PropertyChange option.

✓ Students may ask why properties that are not bound appear in the PropertyNameDialog
window. This question is out to the JavaSoft team—reading the source code in the
BeanBox (BeanBox.java and PropertyNameDialog.java) seems to indicate that the
only properties that should be displayed are the bound properties for the bean. Check the
TickTock and BridgeTester beans. The TickTock bean also displays a property that is not
bound (in addition to the bound property). The BridgeTester bean only displays the
property intValue (although there are many bound properties), but the BeanInfo file for
this bean specifically sets intValue as the only bound property using isBound(true),
whereas it sets isBound(false) for all other properties. The PropertyNameDialog
window then displays the properties you would expect (that is, only intValue).

Bean Properties 4-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Notes

✓ The only properties that are displayed in the Dialog window for the selected target bean
are the properties with the same property type as the property selected for the source
bean. If no properties are found of this type, an error message is displayed indicating no
suitable properties that could be bound to were found.

4-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Recap of Bound Properties

Figure 4-3 provides a recap of what is required for defining a bound


property for a bean.

Code Pieces for Defining Bound Property abc

private ABCtype abc;


private PropertyChangeSupport support = new
PropertyChangeSupport(this);

//registration methods for PropertyChangeListeners


public void addPropertyChangeListener(PropertyChangeListener pl) {
support.addPropertyChangeListener(pl);
}

public void removePropertyChangeListener(PropertyChangeListener pl) {


support.removePropertyChangeListener(pl);
}

public ABCtype getABC(){


return abc;
}
public void setABC(ABCtype newABC){
ABCtype oldABC = abc;
abc = newABC;
support.firePropertyChange("abc", oldABC, newABC);
}

Listener InterfacePropertyChangeListener
EventPropertyChangeEvent
Handler methodpropertyChange(PropertyChangeEvent evt)
Utility classPropertyChangeSupport

Figure 4-3 Recap of Defining a Bound Property

✓ The second box above indicates the listener interface, event type, and handler method
that are used when implementing a bound property. The utility class
PropertyChangeSupport provides an easy way to implement the listener interface and
fire the required event.

Bean Properties 4-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Constrained Properties

Overview
Changes to a constrained property Y result in notification to registered
VetoableChangeListeners. A listener validates the change and if the
change is not appropriate (not allowed), the listener throws a
PropertyVetoException.

The source bean is responsible for catching the exception and reverting
to the old value of the property.

The order in which things are done within the setXXX method for the
constrained property is important.

1. Save the old value.

2. Notify listeners of the new proposed value, allowing them to


veto the change.

3. If nothing vetoes the change (no exception is thrown), set the


property to the new value.

4-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Constrained Properties

Note – If the property is also a bound property (in addition to being a


constrained property), then after setting the property to the new value
(in step 3), you need to fire a PropertyChangeEvent event to indicate
the value of the property was changed.

✓ Some of the engineers in JavaSoft believe that most constrained properties will also be
bound properties.

Defining Constrained Properties


The accessor methods for a constrained property are defined in the
same way as those for simple properties with the exception that the
setXXX method throws PropertyVetoException. The syntax is:
public void setPropertyName(PropertyType pt) throws
PropertyVetoException;

In addition, the VetoableChangeListener interface (which specifies


event handler method vetoableChange() for handling
PropertyChangeEvent events) is used for notifying registered
listeners of a change in the constrained property.

Bean Properties 4-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Constrained Properties

Handling Vetoes
If a registered listener vetoes a proposed property change by throwing
a PropertyVetoException, the source bean with the constrained
property is responsible for the following:

● Catching exceptions.

● Reverting to the old value for the property.

● Issuing a new VetoableChangeListener.vetoableChange call to


all listeners to report the reversion. (The source bean can choose to
ignore any vetoes resulting from a reversion to the old value.)
✓ Basically, the decision here is that if anything does veto the old value, too bad, it was
alright previously and it will probably retain that value.

4-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Constrained Properties

Using the VetoableChangeSupport Class


The JavaBeans API provides a utility class, VetoableChangeSupport,
for managing the responsibilities of a bean with a constrained
property. Use this class in much the same way you did the
PropertyChangeSupport class for bound properties. The
VetoableChangeSupport class will:

● Keep track of VetoableChangeListeners.

● Call the vetoableChange method on all registered listeners.

● Catch any vetoes (exceptions) thrown by listeners.

● Inform all listeners of a veto by calling vetoableChange again, but


with the old property value as the proposed “new” value.

Bean Properties 4-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Constrained Properties

Registering Listeners
The typical code you would add to your bean definition to handle
registration of VetoableChangeListeners for your constrained
property is:
1 private VetoableChangeSupport vetoes
= new VetoableChangeSupport(this);
2
3 // Registration methods for VetoableChangeListeners
4 public void addVetoableChangeListener(VetoableChangeListener vl) {
5 vetoes.addVetoableChangeListener(vl);
6 }
7
8 public void removeVetoableChangeListener(VetoableChangeListener vl) {
9 vetoes.removeVetoableChangeListener(vl);
10 }

Modifying the Property set Method


One additional change needs to be made within the definition of your
setXXX method for the constrained property. This change is a method
call for firing the PropertyChangeEvent event. The syntax for this
call is:
vetoes.fireVetoableChange(String PropertyName, Object oldValue, Object
newValue);

4-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Constrained Properties

Example of Creating a Constrained Property


Suppose you want to constrain the radius value in the CircleBean—
negative values are not allowed and no radius value over 900 (which
practically fills the entire screen display). The necessary code is shown
below in bold type.
1 package sl291.circle;
2
3 import java.beans.*;
4 import java.awt.*;
5
6 /** A simple Bean that is a Circle with properties to
7 * change color, change radius, calculate circumference
8 */
9
10 public class CircleBean extends Canvas {
11 private Color circleColor = Color.blue;
12 private int radius;
13 private double circum;
14
15 private PropertyChangeSupport support = new
16 PropertyChangeSupport(this);
17 private VetoableChangeSupport vetoes = new
18 VetoableChangeSupport(this);
19
20 //registration methods for PropertyChangeListeners
21 public void addPropertyChangeListener(PropertyChangeListener pl) {
22 support.addPropertyChangeListener(pcl);
23 }
24
25 public void removePropertyChangeListener
(PropertyChangeListener pl) {
26 support.removePropertyChangeListene pcl);
27 }
28 // Registration methods for VetoableChangeListeners
29 public void addVetoableChangeListener(VetoableChangeListener vl) {
30 vetoes.addVetoableChangeListener(vl);
31 }
32
33 public void removeVetoableChangeListener(VetoableChangeListener vl){
34 vetoes.removeVetoableChangeListener(vl);}

Bean Properties 4-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Constrained Properties

Example of Creating a Constrained Property (Continued)


35 // Code omitted—Constructor, paint(), getColor(), getRadius methods
36
37 public void setColor(Color newColor) {
38 Color prevColor = circleColor;
39 circleColor = newColor;
40 support.firePropertyChange("color", prevColor, circleColor);
41 repaint();
42 }
43
44 public void setRadius(int r) throws PropertyVetoException {
45 int prevRadius = radius;
46 if (r < 0) {
47 System.out.println("Negative radius not allowed!";
48 } else {
49 //arguments must by of type Object so use wrapper class
50 //for int - Integer
51 Integer prevValue = new Integer(prevRadius);
52 Integer newValue = new Integer(r);
53 vetoes.fireVetoableChange("radius", prevValue, newValue);
54 // no one vetoed, so make the change
55 radius = r;
56 circum = 2 * 3.14159 * radius;
57 System.out.println("Circumference: " + circum);
58 repaint();
59 }
60 }
61 // remaining code omitted

4-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Constrained Properties and Validation

By Source or Listener?
What property changes should be validated by a bean itself and what
property changes should be validated by external listeners? It is not
efficient for a bean to register itself as a VetoableChangeListener to
check for negative values on the radius if it “knows” that negative
values are invalid (as with negative radius values). In these cases, the
bean itself (within the setRadius() method) checks for a negative
property value, and disallows the change (optionally throwing an
exception).

Any other proposed property changes are fired off to registered


listeners using vetoes.fireVetoableChange.

Bean Properties 4-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Constrained Properties and Validation

Validating the Property Change


A listener would implement the VetoableChangeListener interface
and define the vetoableChange method to verify whether the
indicated property change was allowed. For the conditions placed on
the radius of the CircleBean, the CircleVetoer might be:
1 package sl291.circle;
2 import java.beans.*;
3 import java.awt.*;
4
5 public class CircleVetoer extends Label
6 implements VetoableChangeListener
7 {
8 public CircleVetoer () {
9 super("Circle Vetoer");
10 }
11
12 public void vetoableChange(PropertyChangeEvent evt) throws
13 PropertyVetoException {
14 int newValue = ((Integer) evt.getNewValue()).intValue();
15 if (newValue > 900)
16 throw new PropertyVetoException("Radius value > 900",
17 evt);
18 }
19 }
✓ It is possible for a bean to implement VetoableChangeListener itself and define the
vetoableChange method to validate a proposed change in a property. The set method
for the property would then call vetoableChange directly. This means that the bean
itself would validate changes made to its property. The use of the
VetoableChangeSupport class is not necessary in this case if you do not want other
listeners. This is how the original solution to the lab exercise was written; the current
solution supplies a DataTableVetoer bean.

4-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Constrained Properties and the BeanBox

A constrained property adds a VetoableChange choice to the


Edit ➤ Events submenu of the bean. There is no special entry on the
Edit menu for a constrained property as there is for a bound property.
Other Beans become listeners for changes to the constrained property
as they do for any other event on the Edit ➤ Events submenu.

Bean Properties 4-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Recap of Constrained Properties

Figure 4-4 provides a recap of what is required for defining a


constrained property for a bean.

Code Pieces for Defining Constrained Property xyz

private XYZtype xyz;


private VetoableChangeSupport vetoes = new
VetoableChangeSupport(this);

//registration methods for VetoableChangeListeners


public void addVetoableChangeListener(VetoableChangeListener vl) {
vetoes.addVetoableChangeListener(vl);
}

public void removeVetoableChangeListener(VetoableChangeListener


vl) {
vetoes.removeVetoableChangeListener(vl);
}

public XYZtype getXYZ(){


return abc;
}
public void setXYZ(XYZtype newXYZ) throws PropertyVetoException{
XYZtype oldXYZ = xyz;
vetoes.fireVetoableChange("xyz", oldXYZ, newXYZ);
xyz = newXYZ;

Listener InterfaceVetoableChangeListener
EventPropertyChangeEvent
Handler methodvetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException
Utility classVetoableChangeSupport

Listeners define vetoableChange(PropertyChangeEvent evt)


throws PropertyVetoException { ... }
The method will validate the proposed new value for property xyz and throw
PropertyVetoException if the value is not allowed.

Figure 4-4 Recap of Defining a Constrained Property

4-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Properties and the BeanBox

✓ What is described here for PropertySheets and views is specific to the BeanBox. Other
builder tools may use some other interface for displaying and modifying bean properties.

Discovering Bean Properties


The naming conventions used for bean properties enable a builder tool
to discover the properties and behavior of a bean. It is through the
introspection and reflection processes that the PropertySheet window
can be constructed for new beans that you develop (as well as the
construction of the submenus associated with the bean on the Edit
menu of the BeanBox window). Introspection is covered in more detail
in the next module.

Bean Properties 4-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Properties and the BeanBox

Properties on the PropertySheet Window


Only properties with both getXXX and setXXX methods are displayed
on the PropertySheet window of the BeanBox.

Property Editors

A property editor is a class that exists to enable editing of a bean


property. JavaBeans provides the PropertyEditorManager class to
manage a registry of property editors (it maps data types to a property
editor). This registry contains property editors for the following types:
int, float, double, long, short, Number, String, boolean, byte,
Font, and Color.
✓ JavaSoft provides a property editor for the standard types. Property editors display a
value visually as a string or an AWT painted region. Values can be edited by updating the
string or displaying an AWT widget.

The property editor for a property is determined by the get/set


methods for the property.

Note – Developers can create their own property editor. More details
on property editors and creating them is provided in Module 7,
‘‘Customization.”

4-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Properties and the BeanBox

Properties on the PropertySheet Window

Views on the PropertySheet Window

Based on the editor type determined for a property, one of the


following views are displayed in the BeanBox PropertySheet window:

● PropertyCanvas – Uses a Canvas with a rectangle (that displays a


Dialog window when the mouse is pressed) as the view in the
PropertySheet window. This view is used if the associated
property editor defines isPaintable() as non-null. The
ColorEditor and FontEditor provided with the BDK are displayed
with the PropertyCanvas view.

Bean Properties 4-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Properties and the BeanBox

Properties on the PropertySheet Window

Views on the PropertySheet Window (Continued)

● PropertySelector – Uses a Choice component as the view on the


PropertySheet window. This view is used if the associated
property editor defines getTags() as non-null.

The BoolEditor provided with the BDK uses this view. The
molecule demo in the BDK defines its own property editor
(MoleculeNameEditor.java) that also uses this view for
modifying the moleculeName property of the Molecule bean.

● PropertyText – Uses a TextField for the view on the


PropertySheet window. This view is used if the associated
property editor defines getAsText() as non-null.

All string and number-related (integers, floats, doubles, and so


on) properties use this view.

4-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4

Properties and the BeanBox

How a View Is Determined


The view used for a particular property on the PropertySheet window
is determined by checking the associated property editor against the
conditions for the view in the following order: PropertyCanvas,
PropertySelector, PropertyText. The conditions that the property editor
satisfies first result in that view being used on the PropertySheet
window.
✓ The definition of the view (see PropertyCanvas.java, PropertySelector.java, and
PropertyText.java) determines what happens when a change is made to the property
in the PropertySheet window. For example, the PropertyText view extends TextField and
implements the KeyListener interface (defines the keyReleased() method so each
change made to the text field modifies the property of the bean [using the bean’s get/set
methods]). If you replace the listener interface with ActionListener, define the
appropriate methods in the PropertyText.java file, and recompile the BeanBox code
(using gnumake -f GNUmakefile), then after you start the BeanBox, the bean’s
get/set methods for the property are only called when Return is entered in the text field
on the PropertySheet window.

Bean Properties 4-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Properties and the BeanBox

Example of Views
Figure 4-5 illustrates how the different views appear on the
PropertySheet window of the BeanBox. The properties displayed in
the PropertySheet window are for an OurButton bean and a
MoleculeBean.

OurButton Bean Properties

PropertyCanvas
views

PropertyText
views Dialog window

PropertySelector Molecule Bean properties


views

Figure 4-5 Views on the PropertySheet Window of the BeanBox

4-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Defining Bean Properties

Exercise objective – The objective of this exercise is to give you


experience creating different type properties for bean components.
You will add these properties to the beans you created previously.

Preparation
To be prepared for this exercise, you should have completed the
exercise on the event model because you will modify the code written
in that lab. If you did not have time to complete the event model
exercise, use the solutions provided in that exercise to finish your code
and move on to the tasks in this exercise.

Bean Properties 4-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Part 1 - Defining a BoundProperties

Overview
Create a subclass of java.awt.scrollbar and make the "value" property
of this component a bound property. This will make a handy Slider
type component which can be used to input numeric values.

Tasks
1. Change to the $HOME/SL291files/work directory.

2. .Create a subclass of java.awt.Scrollbar called Slider in a source


file called Slider.java.

3. Create the methods and fields required for this class to have
bound properties. For example:
addPropertyChangeListener().

4. Override the method setValue() to fire the


propertyChangeEvent() method. Call setValue() method on
the slider object every time an adjustment event is generated.
(You will need to create an AdjustmentListener.)

Note – AWT scrollbars do not have much default behavior. In order to


get standard behavior out of them, you will need to create an
AdjustmentListener and call setValue() on your scrollbar everytime
an adjustment event is fired.

5. Execute jam.
% jam -sjf=slider.jam

6. Launch the BeanBox.

7. Drop a slider into the BeanBox. (Resize it if you want.)

4-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Part 1 - Defining a BoundProperties

Tasks (Continued)
8. Drop the Juggler bean into the BeanBox.

9. Select the Slider, and choose the Bind Property... menu item.

10. Slide the scrollbar back and forth to make the juggler go faster or
slower.

Bound property Juggler


Slider
responds to value change
by altering rate

Figure 4-6 Overview of Slider Hookup

Bean Properties 4-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Part 2 - Constrained Properties

Tasks

Adding Property Types to a Bean

1. Change to the SL291files/work directory.

2. Edit the DataTableBean.java file to add the following property


types:

▼ Add a Boolean property called constrained that indicates


whether the table is allowed to be resized. If constrained is
true, the resizeTable() method returns without resizing the
table.

▼ Add a read-write property for the cell size in the table. When
the cell size is changed, the table should be resized with the
new cell size (unless constrained is true, of course).

▼ Add methods for getting and setting the number of rows and
columns in the table.

Make the properties for the setting of the rows and columns
constrained properties. Use the VetoableChangeSupport class
for managing the VetoableChangeListeners.

3. Edit the table_manifest.tmp file to add the following:

Name: sl291/dataTable/DataTableVetoer.class

Java-Bean: True

DataTableVetoer Bean

A DataTableVetoer bean has been provided for you. This bean will
validate the values for the number of rows and columns. The number
of rows or columns cannot be less than one. In addition, a 1 x 1 table is
not allowed

4-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Defining Bean Properties

Tasks

Testing Your Beans

1. Regenerate the JAR file for the DataTableBean bean.


% jam -sjf=dataTable.jam

2. Restart the BeanBox or load the new JAR file into the BeanBox
using File ➤ Loadjar.

3. Create instances of the new DataTableBean and the


DataTableVetoer bean.

4. Connect the DataTableBean bean to the DataTableVetoer bean (as


you did for the CircleBean).

vetoableChange DataTableVetoer
DataTableBean
handles change events with
vetoableChange

Figure 4-7 Overview of DataTableBean Hookup

5. Select the DataTableBean and change its rows and column


values.

What happens when you set rows or columns to 0?

What happens when you set rows or columns to a new value


when constrained is set to true?

Bean Properties 4-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Exercise: Defining Bean Properties

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

4-42 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Check Your Progress

Before moving on to the next module, check that you are able to
accomplish or answer the following:

❑ What is a bean property and what are some examples of bean


properties?

❑ Compare the different types of bean properties.

❑ What are the naming conventions used for bean properties and
why is this significant?

❑ What determines if a property is read-only, read-write, or write-


only?

❑ Create a bean component with a bound property.

❑ Create a bean component with a constrained property.

Bean Properties 4-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
4
Think Beyond

What exactly is introspection? How does it work to discover the


properties and behaviors of a bean?

4-44 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Introspection 5

Course Map
This module discusses introspection—the process that is applied to a
JavaBeans component to discover its events, properties, and methods.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

5-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Relevance

✓ Present the following scenario to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – Developers like yourself feel strongly about the amount


of extra work often required to document code and write special
methods just to make it reusable by others.

Imagine that the designers of the JavaBeans specification questioned


you on how to make information about the methods, properties and
events of your application visible to both builder tools and other
developers.

Consider the following options, which do you think would work best?
Why? Any ideas how it all could work?

● In keeping with the platform independence concept, why not


create a simple text format that developers could save information
in about how their component is structured and what methods
and other information is available?

● The Java programming language is a byte-code interpreted


language, which stores information about method names and their
argument and return types. Can this fact be used to enable others
to “learn” how a component is structured?
• The second option is a superior choice, and another reason why the Java
programming language is such a great language. The Beans team did take the advice
of other developers and decided that it would be far more work to keep a separate file
up-to-date with information about a component, and it still would not meet localization
needs. Instead, the introspection and reflection classes and packages were created to
allow a builder tool or a developer to examine the component “automatically” at
runtime to figure out how it can interact with other components.

• This discussion should provide a transition to get students thinking about how a
builder tool can learn about the way a Bean’s properties, methods, and events can
interact with other Beans in the system. In other words, how introspection and
reflection work to make this all happen.

5-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Objectives

Upon completion of this module, you will be able to:

● Define introspection and reflection.

● Analyze the relationship between introspection and the naming


conventions used for properties, methods, and events.

● List several ways in which supplying a class for a Bean can


improve its usability.

● Describe how the process of introspection works.

● Create BeanInfo classes for Bean components.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans 1.0 API specification. [On-line]. Available:


http://splash.javasoft.com/beans/spec.html.

● The Java Core Reflection Specification and API. [On-line].


Available:
http://java.sun.com/products/jdk/1.1/docs/guide/
reflection.

Introspection 5-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Introduction to Introspection

What Problem Does Introspection Solve?

The Code Integration Problem

Since the early beginnings of the Java programming language,


developers have been exchanging applets and classes with great
enthusiasm. As a language like the Java programming language
matures, programs you develop with it are more likely to contain
objects or features that have already been implemented by other
developers. This is especially good news for developers who are under
pressure to produce a complex application quickly. If they can
somehow leverage modular existing code, they can focus on solving
new problems that represent added value for their application, rather
than” reinventing the wheel,” right? Well, this task has not been an
efficient one until recently.

5-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection

What Problem Does Introspection Solve?


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 the
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 source into an application.

The JavaBeans Vision

JavaBeans applies technology and straightforward standards to solve


the problem of code integration. With JavaBeans, Sun™ fosters two
outcomes.

● Java developers will embrace JavaBeans as a paradigm for all


software development. Applications will be composed from
tightly integrated parts called software components. These
components will be designed for reuse beyond the original
application context. All these JavaBeans will be visually
customizable within a development context.

● Companies will create state-of-the-art Integrated Development


Environments (IDEs) and Rapid Application Development (RAD)
applications that support the development of both individual
JavaBeans components, and large applications composed from an
assortment of JavaBeans components. See Module 11, ‘‘Business
Environment for JavaBeans” for a discussion of these tools.

How Introspection Makes the JavaBeans Vision a Reality

JavaBeans relies upon the introspection process to address the major


code integration issues that used to stand in the way of simple,
straightforward software component reuse. Now that JavaBeans
addresses these issues developers are able to create better, more
complex applications in less time than ever before. In addition,
JavaBeans are designed to be “write once, re-use anywheresm.”

Introspection 5-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Introduction to Introspection

Introspection Addresses Key Issues


One issue that thwarts code reuse stems from the reality that different
developers have radically different coding styles. The naming of
accessor and mutator methods for a given class or applet, and the
means for altering the behavior of existing code, follow no predictable
pattern. Some developers use fields liberally to control the state of
their components. This means that a change in a variable such as the
foreground color of a button could clash with the background and
leave no means for that change in state to notify the component or the
environment within which the component is used. When a developer
provides a set of methods for changing an attribute like background,
the notification problem is solved, yet an unpredictable assortment of
names is used for these methods.

5-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection

Introspection Addresses Key Issues (Continued)


A second issue involves the event propagation model that existed
prior to the introduction of JDK 1.1 as the only option for event
handling. It created a lot of extra work for a developer who wants to
interconnect the events of several components that were never meant
to work together. The new event delegation model—designed with
JavaBeans in mind—provides a way to interconnect components
elegantly and efficiently.

A third issue, also addressed with the introduction of JDK 1.1, is the
lack of support for the examination and invocation of methods on a
class at runtime for which there was no compile-time information.

These issues represent a general lack of standards which leave


developers with neither a simple nor an automated system for writing
components that are highly reusable, and provide sufficient clues
about themselves for automated builder tools to follow. Introspection
addresses these challenges and facilitates software component reuse
and development. It will be useful to define some terms before
proceeding.

Introspection 5-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Introduction to Introspection

Definitions

Reflection

Reflection is an API that allows the structure of a class to be determined


and manipulated dynamically at runtime. By using methods in the
class java.lang.Class, a program can obtain a complete list of
instance variables, methods, super classes, and interfaces supported by
any Java type.

Naming Conventions

Naming conventions define a set of rules for naming properties, events,


and methods. In the context of this course it is used in place of what
the JavaBeans specification calls design patterns.

5-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introduction to Introspection

Definitions

Introspection

Introspection is the process of applying reflection to naming


conventions and BeanInfo classes to determine features of a Bean that
relate to its properties, events, and methods.

BeanInfo

BeanInfo is an interface in the java.beans package. The BeanInfo


interface defines a set of methods that allow Beans implementors to
provide explicit information about their Beans. By specifying a
BeanInfo for a Beans component, a developer can hide methods,
specify an icon for the toolbox, provide descriptive names for
properties, define which properties are indeed bound properties, and
much more as described later in this module.

In many cases, all the information a developer would want a builder


tool to know about a Bean is found through reflection without
additional help. In fact, the BeanBox builds a BeanInfo object that
fully describes loaded Beans. It is constructed by combining the
reflective information with any developer-specified BeanInfo data.

Introspection 5-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Sample Uses for BeanInfo

Even though reflection can fill out a BeanInfo quite thoroughly with
information, a Bean developer often wants to influence the set of
information obtained by reflection. Here are some common examples:

● Limit a long list of properties or events to a few important ones.

● Provide a graphics interchange format (GIF) image as an icon that


distinguishes different Beans from each other on a builder tool’s
component palette.

● Add descriptive, human-readable, and possibly even localized


names for properties.

● Affect advanced options such as making properties “hidden” or


“expert” to accommodate different modes of development.

● Specify additional “smart” customizer classes beyond what the


builder tool provides, so that a developer is helped through a
decision tree of property changes for your Bean.

5-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

The Introspector

While explaining the process of introspection, it is useful to


imagine an entity called the Introspector. The Introspector is
what carries out the process. Soon you will come to know
introspection more intimately as the getBeanInfo() method,
defined within the java.beans.Introspector class. The
Introspector follows an elaborate plan for filling out Descriptor
classes which describe the properties, events, and methods of a
Bean. The plan operates in roughly two distinct phases.

First the Introspector locates any descriptor information that has


been explicitly supplied by the developer through BeanInfo
classes. These classes are identified by naming conventions. The
Introspector identifies a class called MyComponentBeanInfo as
the BeanInfo for the Bean named MyComponent.

Second, the Introspector uses various facilities of the core


Reflection API to determine the names of the methods in any
given Bean class. It then applies the naming conventions to
determine what properties the Bean has, the events to which it
can listen, and those which it can send.
✓ The BeanNameBeanInfo convention is required.

Introspection 5-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Summary of the Introspection Process

Three Key Concepts of Introspection


The introspection process could be summarized as follows:

“Paint a picture of a Bean with any information on properties, events,


and methods explicitly supplied by BeanInfo classes, then fill in any
blank spots on the canvas by applying reflection against naming
conventions.”

Each of the key concepts involved in introspection can be summarized


as follows.

● Naming conventions – A set of specified rules or guidelines; for


instance, naming conventions for how accessor and mutator
methods relate to the concept of properties.

These naming conventions are described in the JavaBeans


specification as a set of design patterns or guidelines for
designing Beans.

5-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Summary of the Introspection Process

Three Key Concepts of Introspection (Continued)


● BeanInfo – The class java.Beans.SimpleBeanInfo implements
the interface java.Beans.BeanInfo. Developers that provide a
BeanInfo file for a Bean usually create a class that extends
SimpleBeanInfo.

By creating a BeanInfo class for a Bean, a developer can provide


specific information beyond what is determined through
reflection.
✓ Do not let students involve you in a detailed discussion on what BeanInfo is and does
yet!

✓ Here is a concise outline of the steps involved: When java.Beans.instantiate() loads a Bean, a
method named java.beans.Introspector.getBeanInfo() searches for classes whose names looks
like BeanNameBeanInfo. Such a class extends the SimpleBeanInfo class (which
implements the java.Beans.BeanInfo interface). Normally, getBeanInfo uses reflection to
determine all information about a Bean, but SimpleBeanInfo provides a set of accessor
methods the developer can override to affect the way a Bean’s properties, events, and
methods are used within a builder tool.

● Reflection – Ability of code, such as a component integration


application (builder tool), to examine and analyze about other
code. Reflection is an important part of introspection because it
can probe the structure of a class for methods adhering to naming
conventions.

Reflection is provided by the Core Reflection API in


java.lang.Class and java.lang.reflect.
✓ Reflection is used to study property accessors, event sources, or public methods.
Reflection is applied to the class’s superclass and possibly up its chain. In this way,
information on whether there is a BeanInfo class or not is gathered, so that the Bean can
be used to its full extent in a design environment.

✓ The end of this module contains an overview of reflection. Even though getBeanInfo()
uses reflection to build its own internal BeanInfo so it can do things such as fill out
property sheets, Bean developers are removed from this. The need for Reflection API
utilities arises in subtle ways when a specific Bean requires intimate knowledge about a
class.

Introspection 5-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Summary of the Introspection Process

Three Key Concepts of Introspection

Automatic Analysis
Automatic analysis is a term used to describe the entire process of
introspection on a Bean. It includes the three key concepts: naming
conventions, BeanInfo, and reflection.

The next section covers the naming conventions that reflection uses to
determine what properties, events, and methods a Bean has. Once
these naming conventions have been covered, a discussion of what a
BeanInfo class can specify will make more sense.

5-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Properties

Bean properties are attributes of a component that the designer has


supplied as a means for changing its state. When reflection is used to
determine properties, it searches for public methods that follow certain
naming conventions.
✓ The JavaBeans specification refers to these naming conventions as design patterns. This
term has been avoided because of its connection with the popular term meaning “higher-
level design elements.” The term naming conventions is not perfect either. Design
conventions is close too, but naming conventions was chosen for this course.

✓ For anyone desiring more information, “design patterns” can be characterized as “A


description of communicating objects and classes that are customized to solve a general
design problem in a particular context” according to the authors of Design Patterns, Elements
of Reusable Object-Oriented Software.

Introspection 5-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Properties

Simple Properties
Simple properties are the most common properties used by
components. Mutable properties appear on a GUI element called a
property sheet as names next to fields that are of various object or
primitive types such as, String, int, Color, Float and the like. The
designer indicates properties that may be changed or customized by
creating methods of the form:
public PropertyType getPropertyName() { code }
public void setPropertyName(PropertyType a) { code }

When a property is changed in a builder tool or programmatically,


these get and set methods are used. For example, the following code
would be used for the “foreground” property of a component:
public Color getForeground() { code }
public void setForeground(Color fc) { code }

A charting component might provide access to its chartType so you


can determine whether the chart is configured as an Area, Bar, Line,
XY or other type of chart:
public String getChartType() { code }

Certain capitalization conventions are followed when the Introspector


locates information, such as a pair of accessor and mutator methods,
that implies the existence of a property. For example, the previously
mentioned getForeground() method implies the existence of a
“foreground” property. Additional details about naming conventions
and the APIs are covered in the JavaBeans specification.

5-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Naming Conventions for Properties

Boolean Properties
Boolean properties are really a subset of simple properties since a
boolean is just another object type; however, it has a well-defined
function as a property. Since a Boolean property can only be true or
false, it makes sense to supply an alternate naming convention to the
get/set syntax.

The naming convention for a Boolean property matches the pattern:


public boolean isPropertyName() { code }
public void setPropertyName(boolean b) { code }

For example, the method isOn() makes more sense than getOn()
when used in a conditional:
if ( ! lightBulbBean.isOn() )
lightBulbBean.setOn ( true );
✓ A note of caution; it is possible to have both a getPropertyName() and an
isPropertyName() method. Choose your method names wisely based on an
understanding of the naming conventions.

Introspection 5-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Properties

Indexed Properties
Sometimes it makes sense for a property to actually be an array of
properties or objects. Indexed properties enable the accessor to specify
an element of a property they want to read or write.

Indexed properties are specified by methods of the form:


public PropertyElement getPropertyName(int index){ code }
public void setPropertyName(int index, PropertyElement element)
{ code }

and
public PropertyElement[] getPropertyName() { code }
public void setPropertyName(PropertyElement[] element){ code }

5-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Naming Conventions for Properties

Indexed Properties (Continued)


Note that the distinction between the get and set methods for
indexed properties is a subtle one. For the get method, either it has an
argument that is the array index of the property, or it returns an array.
The set method has either two arguments, an integer array index and
the property element object that is being set, or it has the entire array
as an argument.

For example, up to four methods are possible for an indexed property


that represents a team of employees.
public Employee[] getTeam() { code }
public void setTeam( Employee[] employees) { code }
public Employee getTeam(int index) { code }
public void setTeam(int index, Employee employee) { code
}

Introspection 5-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Events

Multicast Event Sources


The multicast, (meaning “one to many”) model is the default for Bean
components, and the JDK event delegation realm. A multicast event
source is one that can send its events to many listeners. For example, a
Reset button within a Control Bean might result in a call to a reset()
method on an Animator Bean as well as a Timer Bean that has been
configured to control the frame rate of the animation.

The Introspector searches for the following method names to


determine if a Bean is an event source. (A builder tool might use these
methods to allow the user to hook one Bean that fires an event to
another Bean that is listening for the event.)
public void addEventNameListener(EventNameListener l){ code }
public void removeEventNameListener(EventNameListener l){ code }

5-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Naming Conventions for Events

Multicast Event Sources (Continued)


For example:
public void addResetListener(ResetListener al){ code }
public void removeResetListener(ResetListener rl) {code}

The majority of sources that can send events to one listener can also
send them to multiple listeners. For example, the Reset button event
could be sent to multiple Animator Beans if multiple add listener calls
were made with different animator objects.
resetButton.addResetButtonListener(anAnimator1)
resetButton.addResetButtonListener(anAnimator2)
resetButton.addResetButtonListener(anAnimator3)

Introspection 5-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Events

Unicast Event Sources


A unicast event source and listener is used when the designer wants
one and only one listener to be attached to a source. To enforce this
requirement, the designer utilizes an exception that gets thrown if an
attempt is made to add more than one listener to a source.

The Introspector searches for the following method naming


convention to determine if a Bean is a unicast event source:
public void addEventNameListener(EventNameListener enl)
throws java.util.TooManyListenersException { code }
public void removeEventNameListener(EventNameListener enl){ code }

5-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Naming Conventions for Events

Unicast Event Sources (Continued)


For example:
public void addStockQuoteListener(StockQuoteListener sql)
throws java.util.TooManyListenersException { code }
public void removeStockQuoteListener(StockQuoteListener sql) { code }

Introspection 5-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Naming Conventions for Methods

All public methods are accessible by builder tools, scripting


environments, and any other environment that supports Beans.

These public methods are identified and used for purposes such as
matching an event listener to an event source so that the appropriate
method is involved in firing the event.

Capitalization Rules
There are some miscellaneous rules that apply to capitalization for a
property name versus the accessor and mutator names. For instance,
public setForeground(Color c) indicates that there is a property
named foreground, not Foreground. For naming conventions applied
to properties and events that start with multiple capital letters such as
URLLocation, the decapitalize() method normally used within the
Introspector class does not result in changes. These conventions
result from strong reviewer input that JavaBeans should preserve the
style of beginning field names with lowercase letters.

5-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Naming Conventions for Methods

Now that the topic of naming conventions for Bean development has
been covered, you should have a better idea of what kinds of methods
and classes a Bean should have. A computer is even better than a
human at following these kinds of rules. The JavaBeans API supplies a
convenient method, getBeanInfo(beanName), that builder tools and
other automated environments can use any time they want detailed
information about a Bean.

Figure 5-1 shows some of the packages, classes, and methods you will
examine to understand how automatic analysis occurs.

Figure 5-1 Relationship Between Classes and Concepts

Introspection begins with the creation of a Bean so the discussion will


begin with the Beans.instantiate() method.

Introspection 5-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Beans.instantiate Method

Consider the situation in which you are running your favorite


component builder tool and need a pie chart. You pull up your
component palette with a list of component icons and click on your
favorite pie chart component. You then place it on your workspace
and are ready to customize it and link it with the rest of your
application.

At this point a couple of important events occur transparently. First,


the builder tool instantiates the Bean by using code similar to the
following:
1 beanName = "beanco.chart.PieChart";
2 bean = (Component) Beans.instantiate( classLoader, beanName);

This code loads the pie chart Bean using the class loader (potentially
from a JAR file, a local disk, or a remote URL). (You will get into
details about ClassLoader later in Module , “.”) This is the first
argument to the Beans.instantiate method.

5-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Instantiation Supports Customized Beans and Applets

The second argument to the Beans.instantiate method, beanName,


can be different types: a serialized file, a class file, or an applet. In the
example on page 26, the instantiate method first attempts to locate
a beanco/chart/PieChart.ser file that represents a serialized,
customized version of a pie chart. If a serialized Bean is located, then
the Bean is loaded from the file or URL as an object stream.

If no serialized Bean is found, then the instantiate method searches


for a class file named beanco/chart/PieChart.class.
✓ Always specify a .class or .ser file with “.” separators, not “/” separators. Never
include the .class or .ser extensions as part of the string.

Introspection 5-27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Instantiation Supports Customized Beans and Applets

The need for serialized Bean support is evident if you consider that a
generic Chart Bean might contain customizable options which allows
it to become different types of charts—for instance, a bar chart, a line
chart, or a pie chart. In a builder tool, the Chart can be customized by
setting its type property to pie and saving the Bean to disk as a
serialized object. An application that calls
Beans.instantiate("beanco.chart.PieChart") can use the
PieChart Bean whether it was coded manually or whether it is,
instead, the customized state of a more generic Chart Bean.

As a special case, the Bean class file can also be an applet. Applet class
files resolve just like normal Beans, except that the instantiate
method activates some extra code to support a running applet, and
attempts are made to accumulate information that would ordinarily be
supplied in an HTML file’s APPLET tag as a CODE, CODEBASE, ARCHIVE,
or OBJECT attribute.

5-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Introspector.getBeanInfo Method

What happens next? The builder must provide customization options


for the pie chart. It might provide a property sheet for the chart’s
appearance options: two-dimensional versus three-dimensional,
default units, orientation, and so on. It might also want to identify the
chart as a listener for some sort of DataEvent that sends the chart a
new dataset and label information. This event information might be
merged into an Events menu on the builder’s menu bar.

So the builder tool executes code similar to the following:


1 beanClass = Class.forName("beanco.chart.PieChart");
2 BeanInfo bi = Introspector.getBeanInfo(beanClass);

The call to getBeanInfo results in the introspection process obtaining


all of the BeanInfo information provided for the Bean.

Introspection 5-29
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introspector.getBeanInfo Method

Information Discovered by getBeanInfo


You can see exactly what sort of information is discovered through
introspection for a given Bean by using the Edit ➤ Report menu
option of the BeanBox. Below is an abridged version of the report for
the DataTableBean you worked with in Module 4.
CLASS: sl291.dataTable.DataTableBean

Properties:
rowsintgetRows/setRows
cellSizeintgetCellSize/setCellSize
foregroundclass java.awt.ColorgetForeground/setForeground
backgroundclass java.awt.ColorgetBackground/setBackground
fontclass java.awt.FontgetFont/setFont
nameclass java.lang.StringgetName/setName
colsintgetCols/setCols
constrainedbooleangetConstrained/setConstrained
...

Event sets:
vetoableChangeaddVetoableChangeListener/removeVetoableChangeListener
vetoableChange

mouseaddMouseListener/removeMouseListener
mouseClicked
mousePressed
mouseReleased
mouseEntered
mouseExited
...

5-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Introspector.getBeanInfo Method

Information Discovered by getBeanInfo (Continued)


Methods:
public void sl291.dataTable.DataTableBean.
removeVetoableChangeListener(java.beans.VetoableChangeListener)
public synchronized void sl291.dataTable.DataTableBean.setRows
(int) throws java.beans.PropertyVetoException
public boolean sl291.dataTable.DataTableBean.getConstrained()
public void sl291.dataTable.DataTableBean.
addVetoableChangeListener(java.beans.VetoableChangeListener)
public int sl291.dataTable.DataTableBean.getCellSize()
public void sl291.dataTable.DataTableBean.
fireDataTableEvent(sl291.dataTable.DataTableEvent)
public synchronized void sl291.dataTable.DataTableBean.
setCellSize(int)
public synchronized void sl291.dataTable.DataTableBean.setCols(int)
throws java.beans.PropertyVetoException
public synchronized void sl291.dataTable.DataTableBean.
setConstrained(boolean)
public int sl291.dataTable.DataTableBean.getCols()
public int sl291.dataTable.DataTableBean.getRows()
...

Introspection 5-31
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

SimpleBeanInfo Class

The SimpleBeanInfo class implements the BeanInfo


interface and defines the methods described in Table 5-1.
BeanInfo classes that are created for a Bean usually extend
the SimpleBeanInfo class. The SimpleBeanInfo class is a
convenience class that implements all of the BeanInfo
methods, so that each returns null.

This saves you the tedium of implementing many null


methods for each BeanInfo class just so getBeanInfo will
use reflection to obtain information you do not provide.

5-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
SimpleBeanInfo Class

Table 5-1 Methods Specified by the BeanInfo Interface

Method Description

getBeanDescriptor() Returns a BeanDescriptor class used to specify a


Bean’s customizer class.
getAdditionalBeanInfo() This method allows a BeanInfo object to return an
arbitrary collection of other BeanInfo objects that
provide additional information on the current Bean.
This can also be used to force reflection to occur
normally and to determine information using an
additional BeanInfo object to hold supplementary
information about a few specific properties, events, or
methods.
getPropertyDescriptors() This method returns the array of PropertyDescriptor
classes. Each property descriptor represents special
information your Bean provides on a specific property.
getDefaultPropertyIndex() A Bean may have a “default” property that is most
commonly chosen for initial updates by users who are
customizing the Bean. A builder tool might support this
by giving the default property’s field focus on the
property sheet.
getEventSetDescriptors() An array of EventSetDescriptors classes is returned
by this method. Similar to PropertyDescriptors, each
event descriptor controls how a builder tool allows the
user to interact with your Bean’s events.
getDefaultEventIndex() A Bean can have a “default” event that is most
commonly used by humans when employing the Bean.
A builder tool might choose to support this by
highlighting this event in a list of potential events the
user can select from when connecting sources to targets.
getMethodDescriptors() This method returns a set of MethodDescriptors. You
can use this to specify localization information about the
name of your methods or their parameters.
getIcon(int) This method returns an image object that can be used to
represent the Bean in toolboxes or toolbars. You can
supply various sizes and bitmaps for your Bean to
accommodate different builders or various user
environments such as lower resolution displays.

Introspection 5-33
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

A BeanInfo Class That Affects Properties

To understand what parts make up this mysterious BeanInfo class as


well as why you might want to add a BeanInfo class to your Bean,
revisit the CircleBean example and create a CircleBeanBeanInfo
class. In the following code, the information that getBeanInfo()
locates is influenced when it searches for a set of property descriptors
returned by the getPropertyDescriptors() method of the
BeanInfo class.

5-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
A BeanInfo Class That Affects Properties

1 package sl291.circle;
2
3 import java.beans.*;
4
5 public class CircleBeanBeanInfo extends SimpleBeanInfo {
6 public PropertyDescriptor[] getPropertyDescriptors() {
7 try {
8 PropertyDescriptor props[] = {
9 new PropertyDescriptor("radius", CircleBean.class)};
10
11 props[0].setDisplayName("Radius of circle");
12 props[0].setBound(true);
13
14 return props;
15 } catch (IntrospectionException ex) {
16 ex.printStackTrace();
17 return super.getPropertyDescriptors();
18 }
19 }
20 }
21 }

Introspection 5-35
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

A BeanInfo Class That Affects Properties

Overriding the getPropertyDescriptors Method


This class extends SimpleBeanInfo and is very short. In this class,
you provide information that is different from what the normal
automatic process of introspection would discover. Here, the only
method defined is getPropertyDescriptors() which is used to
describe the radius property. This method is designed to return
instances of the PropertyDescriptor describing each property a builder
tool needs to know about.

5-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
A BeanInfo Class That Affects Properties

Limiting Visible Properties


If getBeanInfo() was called on CircleBean with this BeanInfo class
available, the number of properties displayed in the PropertySheet
window of the BeanBox would be just one. You would no longer see
the font or name properties. This is a side effect of a BeanInfo file. To
have all of your Bean properties displayed, you would need to provide
information on all properties or employ the use of
getAdditionalBeanInfo(). An example of the latter is shown on
page 39.

The PropertyDescriptor Class


A look at the documentation for the PropertyDescriptor class will
show that it was created to supply the same sort of information that is
provided by reflection-enforced naming conventions. In fact, all of the
Descriptor classes (BeanDescriptor, EventSetDescriptor,
MethodDescriptor, ParameterDescriptor, PropertyDescriptor,
and the like) extend the FeatureDescriptor class. The
FeatureDescriptor class contains accessor and mutator methods for
configuring obvious things like the name and value or the getXXX()
and setXXX() method names for a property. Note that in this
example, the constructor for PropertyDescriptor was used to
provide only minimal information: the property name radius, and the
class (CircleBean.class) it should search for the remaining
information.

Introspection 5-37
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
A BeanInfo Class That Affects Properties

The setDisplayName Method


Another improvement is that the property’s display name would
change from “radius” to “Radius of circle” as a result of the
setDisplayName("Radius of circle") statement. Perhaps a
redundant name, but still easier to look at.

The setBound Method


The setBound() method enables a Beans developer to explicitly
specify which properties are bound. This enables the BeanBox to limit
the list of properties displayed when attempting to bind a component
to a bound property.

5-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Using getAdditionalBeanInfo

How It Can Be Used


You may have noticed that when you supply a set of property
descriptors with getPropertyDescriptors(), the BeanBox ignores
any properties you have not included in the PropertyDescriptor[]
array. So you might ask:

“If I need to supply a BeanInfo file just to modify one or two of my


properties, then how do I avoid having to list every single one of the
Bean’s properties in the BeanInfo file?”

There is a clean way around this problem using


getAdditionalBeanInfo(). You write a single
BeanNameBeanInfo.java that has a getAdditionalBeanInfo()
method defined. This method points to another BeanInfo class that
defines getPropertyDescriptors() and returns a
PropertyDescriptor[] array describing only the properties you want to
change.

Introspection 5-39
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Using getAdditionalBeanInfo

How It Can Be Used (Continued)


In the following example, the display name of the CircleBean’s radius
is defined to be “Radius of circle,” while all other properties remain on
the PropertySheet window as they would appear if you did not
provide a BeanInfo class. Without employing this technique, the
programmer must define all the properties in the CircleBeanBeanInfo,
or only the radius property would be visible.
1 package sl291.circle;
2 import java.beans.*;
3
4 public class CircleBeanBeanInfo extends SimpleBeanInfo {
5 public BeanInfo[] getAdditionalBeanInfo() {
6 return new BeanInfo[] { new CircleBeanAdditionalInfo() };
7 }
8 }
9 public class CircleBeanAdditionalInfo extends SimpleBeanInfo {
10 public PropertyDescriptor[] getPropertyDescriptors() {
11 try {
12 PropertyDescriptor props[] = {
13 new PropertyDescriptor("radius", CircleBean.class)};
14 props[0].setDisplayName("Radius of circle");
15 props[0].setBound(true);
16 return props;
17 } catch (IntrospectionException ex) {
18 ex.printStackTrace();
19 return super.getPropertyDescriptors();
20 }
21 }
22 }

Alternatively, you can provide CircleBeanAdditionalInfo in a


separate class file. In the JavaBeans specification, the primary use for
getAdditionalBeanInfo() is to force introspection to include other
BeanInfo objects from which your properties, methods, and events
descriptors are composed.

5-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

How a Bean Is Analyzed

A BeanInfo Class That Affects Methods


Just as a BeanInfo that limits the number of properties can be
provided, you can also provide a BeanInfo that limits the number of
methods that are seen when a source Bean selects your Bean as a
target.

Looking at the properties example from the previous module, you


know that the StockDetail Bean, in this example, can be a listener for
StockPriceChangeEvents. If you hook the StockWatch and
StockDetail Beans together in the BeanBox and select StockDetail as a
target, you would choose priceChange() as the method that the
LabelListener implements to pass the StockPriceChangeEvent
object.

To provide priceChange() as the only visible method, provide a


StockDetailBeanInfo class that overrides the
getMethodDescriptors().

Introspection 5-41
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
How a Bean Is Analyzed

A BeanInfo Class That Affects Methods (Continued)


1 package sl291.stock;
2
3 import java.beans.*;
4 import java.lang.reflect.Method;
5
6 public class StockDetailBeanInfo extends SimpleBeanInfo {
7 MethodDescriptor method(String name, Class arg)
8 throws NoSuchMethodException
9 {
10 Method m = StockDetail.class.getMethod(name, new Class[] {arg});
11 return new MethodDescriptor(m);
12 }
13 public MethodDescriptor[] getMethodDescriptors() {
14 try {
15 return new MethodDescriptor[] {
16 method("priceChange", StockPriceChangeEvent.class)};
17 } catch(NoSuchMethodException ex) {
18 ex.printStackTrace();
19 return super.getMethodDescriptors();
20 }
21 }
22 }

This code demonstrates the reflection method getMethod() call that


supplies MethodDescriptor with the actual method object for
priceChange.

5-42 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Details of How a BeanInfo Is Processed

Now that you have studied three scenarios in which a BeanInfo file
was provided for a Bean to override various get methods, you will
examine a general example of a BeanInfo that defines
getEventSetDescriptors().

Probe BeanInfo Classes for Descriptor Information


Given a Bean, MyComponent.class, a check is made to see if
MyComponentBeanInfo.class exists. If it does, a call to
getEventSetDescriptors() is made on that class. A non-null return
value indicates information has been explicitly supplied and
getBeanInfo’s work is nearly done. Otherwise, the Introspector
searches through the inheritance chain of MyComponent and
MyComponentBeanInfo checks whether getEventSetDescriptors()
returns non-null elsewhere. This way the BeanInfo a developer has
supplied for one class carries along any class that extends it. Next, any
explicitly supplied AdditionalBeanInfo classes are checked in the
same way by calling the getAdditionalBeanInfo() method on each
likely BeanInfo class.

Introspection 5-43
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Details of How a BeanInfo Is Processed

Apply Reflection and Naming Conventions


If, at this point, no information has been explicitly supplied within a
BeanInfo class, the method that searches for EventSetDescriptors, for
example, would proceed to use the naming conventions it “knows
about.” Since the JavaBeans specification states that a source must
implement an add and remove method for each event it wants to
receive notification about, the Introspector now employs methods
from the core Reflection API such as getDeclaredMethods() to
search for all the public add and remove methods in this Bean. If
necessary, it uses getMethods() to widen the search for public add
and remove methods all the way up the inheritance hierarchy.

Based on its findings, an EventSetDescriptor is built up “from scratch”


using the results. Hence, the following matching pair of methods
results in the identification of a Foo event:
addFooListener(Foolistener l) { code }
removeFooListener(FooListener l) { code }

Now the BeanBox (or builder tool) has “learned” that it can hook
adaptor Bean event sources for Foo events with Beans that implement
the FooListener interface.

5-44 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Available BeanInfo Methods

You have already seen in Table 5-1 the set of methods that the
BeanInfo interface provides, but there are also many important
methods you will need to know about. For each method in Table 5-1
that returns a descriptor class, there is an additional table that
describes the accessor methods that return specific information about a
property, method, event, or another Bean.

Use Table 5-2, Table 5-3, Table 5-4, Table 5-5, and Table 5-6 as reference
material to help you decide when to create BeanInfo classes that
override and set certain types of information. There are matching
mutator methods for almost all of the following accessors, but in many
cases you will want to use the constructor for a descriptor class such as
PropertyDescriptor() since it can make assumptions and fill out a
lot of the default information.

Table 5-2 Methods Specified by the BeanDescriptor Class

Method Description

getBeanClass() The Class object of the Java class that


implements the Bean; for example,
sun.beans.OurButton.class.
getCustomizerClass() The Class object of the Java class that
implements the Bean’s Customizer; for
example,
sun.beans.OurButtonCustomizer.class

Introspection 5-45
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Table 5-3 Methods Specified by the EventSetDescriptor Class

Method Description

getAddListenerMethod() The method used to register


a listener at the event source.
getListenerMethodDescriptors() An array of
MethodDescriptor objects
for the target methods
within the target listener
interface that get called
when events are fired.
getListenerMethods() An array of Method objects
for the target methods
within the target listener
interface that get called
when events are fired.
getListenerType() The Class object for the
target interface that will get
invoked when the event is
fired.
getRemoveListenerMethod() The method used to register
a listener at the event source.
isInDefaultEventSet() True if the event set is in the
“default set”. Defaults to
“true”.
isUnicast() Normally event sources are
multicast.
setInDefaultEventSet(boolean) Marks an event set as being
in the “default” set (or not).
setUnicast(boolean) Marks an event set as unicast
(or not).

5-46 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Table 5-4 Methods Specified by the PropertyDescriptor Class

Method Description

getPropertyEditorClass() The low-level description of


the method.
getPropertyType() The Java type information for
the property.
getReadMethod() The method used to write the
property value. May return
null if the property cannot be
written.
getWriteMethod() The method used to write the
property value. May return
null if the property cannot be
written.
isBound() Updates to “bound”
properties will cause a
“PropertyChange” event to
get fired when the property is
changed.
setBound(boolean bound) Updates to “bound”
properties will cause a
“PropertyChange” event to
fire when property is
changed.
isConstrained() Attempted updates to
“Constrained” properties
will cause a
“VetoableChange” event to
fire when the property is
changed.
setConstrained(boolean) Attempted updates to
“Constrained” properties
will cause a
“VetoableChange” event to
get fired when the property is
changed.
setPropertyEditorClass(Class) Normally, PropertyEditors
will be found using the
PropertyEditorManager.

Introspection 5-47
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Available BeanInfo Methods

Table 5-5 Methods Specified by the MethodDescriptor Class

Method Description

getMethod() The low-level description of the


method.
getParameterDescriptors() The locale-independent names of
the parameters. May return a null
array if the parameter names are
not known.

Note – All the descriptor classes extend the FeatureDescriptor class.

Table 5-6 Methods Specified by the FeatureDescriptor Class

Method Description

attributeNames() An enumeration of the locale-


independent names of any
attributes that have been
registered with setValue.
getDisplayName() You can associate a short,
localized, descriptive string
with a feature (property, method
or event). Normally these
descriptive strings should be less
than about 40 characters.
getName() The programmatic name of the
property/method/event.
getShortDescription() A localized short description
associated with this
property/method/event. This
defaults to the display name.
getValue(String) Retrieve a named attribute with
this feature.

5-48 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Table 5-6 Methods Specified by the FeatureDescriptor Class

Method Description
isExpert() The “expert” flag is used to
distinguish between those
features that are intended for
expert users from those that are
intended for normal users.
isHidden() The “hidden” flag is used to
identify which features are
intended only for tool use, and
which should not be exposed to
humans.
setDisplayName(String) The localized display name for
the property/method/event.
setShortDescription(String) You can associate a short
descriptive string with a feature.
setValue(String, Object) Associate a named attribute with
this feature.

Introspection 5-49
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Reflection and JavaBeans

You have already seen reflection in action throughout the process of


introspection in this module, as you examined how getBeanInfo()
works. Key methods like getDeclaredMethod() can find a specific
method in a Bean, whereas getMethods() can return all methods,
including those from a Bean’s super-classes. It is worth summarizing
some advantages and features reflection brings, even though many
developers may never need to use the API directly.

Advantages Provided by Reflection


Here is a list of some advantages the core Reflection APIs bring to
JavaBeans:

● Saves you from the tedium of defining and maintaining a full set
of BeanInfo information for your class. Since the use of BeanInfo
is optional, you only use it when something would otherwise be
unclear or in the few cases reflection does not handle, such as
support for providing Bean icons.

5-50 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Reflection and JavaBeans

Advantages Provided by Reflection (Continued)


● Enforces naming conventions by using them as a guide for
discovery of the unique properties, events, and methods a Bean
possesses. This is a key to the success of JavaBeans as a component
technology. Reflection renders the publishing and discovery of
component features a trivial problem for the developer.

● Creates opportunities for scripting and more generic use of


wrapper applications that work on Bean components since mere
strings can specify class types and argument types which
reflection can use with the Class class for instantiation and
invocation. A main stumbling block in the past has been that you
must employ clever and rigid use of abstract classes, and much
information about the classes and methods that might be used had
to be available at compile time.

● For applications that need to discover and use public members of


a target object, given only its runtime instance, methods such as
getField(), getMethod(), getConstructor(), getFields(),
getMethods(), and getConstructors() are provided in the class
Class that utilize the Field, Method and Constructor from the
Reflection API.

Introspection 5-51
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Reflection and JavaBeans

Major Classes of the Reflection API


The following is a list of the major classes of the Reflection API and
their general functions:

● java.lang.Class – New methods for Class support construction


of Field, Method, and Constructor in the Reflection API. Other
methods like getMethods() return the set of methods of a class.

● java.lang.reflect.Method – Provides information about and


access to a single method on a class or interface. There is an
invoke() method that enables a call on a reflected method, such
as those returned by Class.getMethods().

● java.lang.reflect.Constructor – Provides information about


and access to a specific constructor for a class. Constructor
provides a newInstance() method which enables instantiation of
a class using a specific constructor.

● java.lang.reflect.Field – Provides information about and


dynamic access to a single field of a class or an interface. The
reflected field may be a class (static) field or an instance field.
✓ A detailed investigation of the Reflection API is beyond the scope of this module, but
students are encouraged to reference the “Java Core Reflection API and Specification”
which can be found on the http://java.sun.com Web site.

5-52 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Additional Information on Introspection

You might have noticed that only public method signatures have been
mentioned during the discussion of reflection. In fact, reflection works
on all types of methods, but the scope of methods that are visible is
restricted by the security manager (whether it is done within an applet
or within an application).

The Introspector applies reflection to only public methods of a bean;


however, it seeks to apply the naming conventions to all public
methods. The message here is that if you as a designer do not want a
public method to be interpreted as a property, for example, then you
need to either make it non-public, taking care not to name methods
starting with set and get, or provide a getPropertyDescriptors()
method in a BeanInfo that excludes the properties that reflection
would otherwise detect.

The BeanInfo class is provided as the ultimate control point for how
naming conventions are interpreted. It can be used to limit the number
of valid properties and events that are visible from outside the Bean,
or to provide additional information to the Introspector.

Introspection 5-53
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Additional Information on Introspection

Security
Security applies to introspection just as it applies to applets,
applications, packages, and classes in the Java programming language.
The security manager always has control, if that manager is in the Java
Virtual Machine of a browser, instantiated within the Applet Viewer,
or applied, in a very minimal case, in a locally run application.

5-54 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5

Final Words on Introspection

The key point to understand about introspection is that it is the


foundation concept that enables the JavaBeans architecture to be such
an effective component software model.

The way in which the process of introspection is implemented


provides great advantages such as:

● Portability – Everything is done in the Java Platform, so you can


“write components once, reuse them everywhere”. There are no
extra specification files that need to be maintained independently
from your component code. There are no platform-specific issues
to contend with. Your component is not tied to one component
model or one proprietary platform. You get all the advantages of
the evolving Java APIs and maintain the portability of your
components.

Introspection 5-55
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Final Words on Introspection

● Reuse – By following the JavaBeans design conventions,


implementing the appropriate interfaces, and extending the
appropriate classes, your component has reuse potential that
extends far beyond what you ever considered could or would be
done with it.

5-56 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File

Exercise objective – The objective of this exercise is to gain experience


creating your own BeanInfo classes for a Bean.

Preparation
To be prepared for this exercise, you should have completed the
exercise on properties because you now will be adding a BeanInfo file
to the DataTableBean Bean. If you were not able to complete coding
the exercise on Bean properties, use the solutions provided for that lab
exercise to finish your code before beginning this exercise.

Introspection 5-57
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File

Tasks

Controlling a Bean’s Property Information

In an example in this module, you saw how to limit the number of


properties listed in the property sheet to a single property: the radius
of the circle. Realistically, there are other useful properties the circle
Bean has inherited from other components such as its color and the
color of its background.

There are three short objectives in this exercise to help you become
more familiar with the structure of BeanInfo:

● Add the color and background properties to the list of property


descriptors.

● Add display names for these properties that are more descriptive
than “color,” “background,” or “foreground.” (See table below.)

Property Name Display Name

radius Radius of circle


color Fill color for circle
background Color outside circle

● Specify the radius as the “default” property that developers


suggest is the most interesting or useful.

1. Change to the SL291files/work directory.

2. Edit CircleBeanBeanInfo.java and add code to create the two


extra PropertyDescriptor objects that need to be returned by
getPropertyDescriptors().

3. Add support for a call to getDefaultPropertyIndex() to


indicate that radius is the default property.

5-58 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File

Controlling a Bean’s Event Information

The purpose of this exercise is to create a BeanInfo file “from scratch”


for a bean that provides information that is different from, or in
addition to what reflection can provide.

When you hooked the DataTableButton to the DataTableBean in


previous exercises, you may have noticed a large number of target
methods from which to choose. In this exercise, you will learn how to
“hide” the methods that are not used in the exercise by creating a
BeanInfo class that provides information about only the three most
important ones.

Note – As a designer you must be careful when making such decisions


because you never know how a component might be used in the
future.

1. Create a new file in SL291files/work called


DataTableBeanBeanInfo.java.

2. Edit the DataTableBeanBeanInfo class by extending


SimpleBeanInfo.

3. Override the getMethodDescriptors() method to return only


the set of “fire” methods.

You will have to use the constructor of MethodDescriptor by


passing it Method classes obtained by calling getMethod() on
the DataTableBean class.

4. Add the new file to the dataTable.jam makefile classes target


and generate the new Bean using:

% jam -sjf=dataTable.jam

5. Run the BeanBox and test the effects.

Introspection 5-59
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Exercise: Creating a BeanInfo File

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you find you do not have time to spend on discussion, then
just highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they have learned in this exercise to
situations back at their work place.

5-60 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Check Your Progress

Before continuing on to the next module, check that you are able to do
the following:

❑ Define introspection and reflection.

❑ Analyze the relationship between introspection and the naming


conventions used for properties, methods, and events.

❑ List several ways in which supplying a class for a Bean can


improve its usability.

❑ Describe how the process of introspection works.

❑ Create BeanInfo classes for Bean components.

Introspection 5-61
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
5
Think Beyond

This module has given you a foundation to work from. Understanding


what introspection is, and what it means to Beans with respect to the
BeanInfo classes and reflection, places you farther along the path to
understanding Beans than you may realize.

Many new concepts were briefly introduced in this module, and you
can practically chart the road map of the course from them. Here is a
sketch of upcoming modules which will put to use many of the
methods and classes that were discussed in the course of learning
about introspection:

Module 6 – Persistence, how Beans are reloaded from a serialized state

Module 7 – How to write a customizer and a property editor

Module 10 – How to build programs that use Beans outside of the


Beanbox

5-62 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Persistence 6

Course Map
This module discusses the mechanisms for persisting the state of a
bean.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

6-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – The following questions are relevant to the topics


discussed in this module regarding persisting the state of beans:

1. After modifying the appearance of your bean, what can you do


to save its state for later retrieval?

✓ Using the Object Serialization API, which is part of JDK 1.1, you can write out the state of
your bean to a serialized stream for later retrieval. Recall the File ➤ Save menu item
provided by the BeanBox. All of the beans on the BeanBox are written to a serialized file,
and then that file and the hookup classes are written to a JAR file (with the name you
specify in the Save dialog window).

2. How easy is it for the saved state of a bean to be packaged and


used as the initialization of your bean in other applications?
✓ If you write the serialized stream to a .ser file, the .ser file can be packaged in a JAR file
for use by other applications. Any code that wanted to use your bean would unpackage
the JAR file and use readObject(ser file name) or Beans.instantiate with your .ser file
as the second argument. This would create an instance of your bean, with the state you
saved to, in the code.

6-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Objectives

Upon completion of this module, you will be able to:

● Evaluate the goals for bean storage.

● Describe how automatic Java serialization works.

● Evaluate which data fields need to be marked as transient using


serializable rules,.

● Describe the requirements to create persistent storage of objects.

● Add the mechanisms to persist a bean component.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans API 1.0 Specification. [On-line]. Available:


http://splash.javasoft.com/beans/spec.html.

● Object Serialization Specification. [On-line]. Available:


http://www.javasoft.com/products/jdk/1.1/docs/guide/
serialization.
✓ The SL-301 course, Distributed Programming With Java, includes a module on object
serialization. The Externalizable interface is also covered in that course, but is not
addressed here.

✓ The April ‘97 release of the BDK added a new option to the File menu called Serialize
Component which enables you to write out to a serialized stream just a single component
in the BeanBox window and its internal state.

Persistence 6-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Goals for Bean Storage

General Java Object Storage


Almost every application requires some way of keeping data. What if
the data represents a Java object? The main goal of the Java Object
Serialization API is to provide a simple and transparent means of
persisting Java objects.

Object serialization provides a mechanism to write an object onto a


stream and then restore the object to its original state. For example, a
Java application can serialize a Frame window to a diskette on a
Windows machine, a person can transport the diskette to a Solaris
machine, and then a Java application can restore the Frame window to
the exact state which existed on the Windows machine!

The JavaBeans architecture supports the Java Object Serialization


mechanisms. This results in an automatic way of saving and restoring
the state of bean components and applications created using beans.
With JavaBeans architecture, a tool does not have to generate source
code to represent the user actions; instead, the tool can simply serialize
the state of the application as constructed by the user.

6-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Goals for Bean Storage

Bean Storage
Bean components will vary in complexity and use. They will range
from simple beans (that extend a Java AWT component) to more
complex beans that, for example, pretend to be a Microsoft Excel
document inside a Microsoft Word document. Moreover, not all beans
need to have persistent state. But any bean that allows its properties to
be modified should have a way of saving the changes and restoring
the bean with those changes.

The goals for bean storage are to provide not only the automatic Java
serialization mechanisms, but also an “externalization” stream
mechanism. In the latter case, a bean component will have full control
over how its state is written out to the serialized stream. In addition,
the externalization mechanism provides the capability of using
different data formats when writing to the stream.

Note – The Externalizable interface is not covered in this course,


but you can refer to an example of a bean that uses externalization in
the demo/sunw/demo/buttons/ExternalizableButton directory of
the BDK (SL291files/BDK).

Persistence 6-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Java Object Serialization

Serializable Interface
To serialize objects, the JDK 1.1 provides an interface called
java.io.Serializable:
package java.io;

public interface Serializable { };

Serializable interface is known as a tagging interface. Interfaces are


used to define behaviors objects are capable of performing. A tagging
interface is one that does not contain any method declarations. Thus, a
tagging interface simply identifies an object as being capable of
performing in a specified role.

By implementing the Serializable interface, a developer essentially


states that instances of that class may be serialized. By default,
instances of classes are not serializable. When an object is being
serialized, the JVM makes a check to ensure the object implements the
Serialization interface. If the interface is not implemented, an
exception is generated and the serialization process is terminated.

6-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Java Object Serialization

Classes That Are Serializable


Any class is serializable, as long as the class or a parent class
implements java.io.Serializable. Many commonly used JDK
classes support serialization. Examples of serializable classes include
Component, String, Date, Vector, and Hashtable. Thus, any subclass
of Component, 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 IOException.

Note – Since the AWT Component class implements Serializable, all


subclasses are automatically serializable. However, to avoid overhead,
a subclass of any AWT components should implement Serializable.

✓ Objects can be serialized by implementing the Externalizable interface, but this interface
is not covered in this course. Externalizable classes mean that the class is serializable,
but you must provide the methods for reading and writing objects; a default
implementation is not provided.

Persistence 6-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

What Is and Is Not Saved

Bean Properties and Internal State


In general, all exposed properties of a bean should be serialized. In
addition, any internal state created by the bean developer that is not
directly accessible through getXXX and setXXX methods should be
serialized.

Pointers and Event Adapters


References to external beans should not be serialized—these references
should be re-created by higher-level software. For example, references
to event listeners or the information generated by connecting beans
together using events should be tracked by mechanisms provided by
builder tools.

6-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
What Is and Is Not Saved

Fields Automatically Serialized


The Java Object Serialization API automatically serializes most fields
of a Serializable object to the storage stream. This includes
primitive types, arrays, strings, and so forth. The API does not
serialize or deserialize fields that are marked transient or static.
✓ Methods are not written to the storage stream since they are part of the underlying class
definition. It is assumed that the class file will be available when the object is deserialized.

Fields Not Serialized


Fields that should not be serialized must be marked with the
transient keyword. These include classes such as
java.io.FileInputStream, java.io.FileOutputStream, and
java.lang.Threads.

In addition, under JDK 1.1, images are not serialized.


✓ So images should be marked transient. If the serialized stream (.ser file) is packaged in
a JAR file, the images (such as .gif files) can be packaged with the stream and used by
an application when restoring the serialized object.

Note – Fields marked as transient must get restored somehow. For


threads, usually a new initial thread is created. For images, these can
be obtained from the JAR file for the bean. For other types of
transient variables, you must provide some other means for setting
values for these variables when the bean is deserialized, possibly using
the Externalizable interface.

Persistence 6-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

What Is and Is Not Saved

The Keyword transient


Use the keyword transient to indicate that a data field of an object or
bean is not to be serialized. For example,
transient Object anotherField;
private transient String sensitiveData;
private transient Thread animationThread;
private transient Image[] images;

Note – The accessor type (private, protected, or public) has no


affect on whether the data can be serialized. Any private data fields
that are sensitive should be marked private transient.

6-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Input and Output Interfaces

The Java Object Serialization API provides an ObjectOutput interface


for writing and an ObjectInput interface for reading objects to and
from a serialized stream. These interfaces are implemented by the
ObjectOutputStream and ObjectInputStream classes, respectively.

java.io.DataOutput

ObjectOutput ObjectOutputStream

java.io.DataInput

ObjectInput ObjectInputStream

Legend
Class
Interface
Extends
Implements

Figure 6-1 ObjectOutput and ObjectInput Interfaces

Note – The DataOutput and DataInput interfaces are implemented


by streams to write and read, respectively, primitive Java data types to
and from a stream.

Persistence 6-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Please reinsert the new slide:

Saving Beans to Streams

Saving Beans to Streams

ObjectOutputStream Class
Writing Java objects, and a bean component in particular, to a
serialized stream is a simple process. The ObjectOutput interface is
implemented by the ObjectOutputStream class. You can use the
writeObject() method defined by the ObjectOutputStream class to
write out your bean.

The class of the object, the signature of the class, and the values of the
non-transient and non-static fields of the class and all of its supertypes
are written by the writeObject() method. The writeObject()
method throws both IOException and ClassNotFoundException.

6-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Saving Beans to Streams

Example of Code Syntax


The following code can be used as a template for writing your bean to
a serialized stream:
1 public static void main(String args[]) {
2 String serFile = "day.ser";
3
4 try {
5 Date today = new Date();
6
7 FileOutputStream fos = new FileOutputStream(serFile);
8 ObjectOutputStream oos = new ObjectOutputStream(fos);
9 oos.writeObject(today);
10
11 oos.close();
12 fos.close();
13 } catch(IOException e) {
14 e.printStackTrace();
15 }
16 }

Persistence 6-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Retrieving Beans From Streams

ObjectInputStream Class
Deserialization is re-creating an object that has been written out to a
serialized stream by reading the object back from the stream. The
ObjectInputStream class implements the ObjectInput interface and
defines a readObject() method that you can use to deserialize your
object. The readObject() method also throws both IOException and
ClassNotFoundException.

6-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Retrieving Beans From Streams

Example of Code Syntax


The following code can be used as a template for reading your bean
back from a serialized stream:
1 public static void main(String args[]) {
2 try {
3 FileInputStream fis = new FileInputStream("day.ser");
4 ObjectInputStream ois = new ObjectInputStream(fis);
5
6 Date yesterday = (Date)ois.readObject();
7 System.out.println(“The date was: “ + yesterday);
8
9 ois.close();
10 fos.close();
11 } catch(IOException e) {
12 e.printStackTrace();
13 } catch(ClassNotFoundException ex) {
14 //thrown if cannot locate a class used by serialized object
15 ex.printStackTrace();
16 }
17 }

Persistence 6-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Creating a Java Beans Prototype

A JAR file can contain serialized prototypes of beans. Prototyping a


bean enables a new bean component type to be created without
writing any code. To create a prototype, customize an existing bean by
setting its properties and then serializing it to a file. Package the bean
into a JAR file as usual, except the manifest file will contain an entry
for the serialized file name instead of a class name.

6-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Creating a Java Beans Prototype

Packaging a Prototype Bean


Consider the following steps:

1. Create a JellyBean bean in the BeanBox.

2. Change the foreground color to Green.

3. Choose File > Serialize Component... and enter a file name, such
as GreenBean.ser.

4. Create a manifest file called manifest.tmp for the Prototype as


follows:
1 Manifest-Version: 1.0
2
3 Name: GreenBean.ser
4 Java-Bean: True

5. Package the bean into a JAR file:


5 jar cvfm greens.jar manifest.tmp GreenBean.ser

6. Clear the BeanBox and load the new JAR file. A new type called
GreenBean should appear on the Toolbox . Drag a GreenBean
onto the BeanBox; it should appear just as you saved it.

The procedure is pretty straightforward. This example used the


BeanBox, but just about any beans tool should support serializing a
bean’s component to a file. In fact, you could simply write some code
to instantiate the original bean using new, set up its state, and serialize
it to a file. The rest of the steps remain unchanged. Creating the
serialized component is just usually simpler with a tool.

Persistence 6-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6

Deserialization and Class Loaders

It should also be noted that an object can be deserialized from a .ser


file that is associated with a class loader. The beans.instantiate()
method is used in this case. This enables you to package a .ser file
and a set of .class files in a JAR file and have the deserialized object
use the associated .class files.

So you could write out your bean to a .ser file using the
writeObject() method, and instantiate the bean from the .ser file
using Beans.instantiate().

6-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Deserialization and Class Loaders

Using Beans.instantiate()
Using the serialized object from the GreenBean example, here is the
source code to instantiate a GreenBean using Beans.instantiate():
1 public static void main(String args[]) throws Exception {
2 Component c = (Component)Beans.instantiate(null,
"sl291.GreenBean");
3 Frame f = new Frame();
4 f.add(c, BorderLayout.CENTER);
5 f.setSize(200, 200);
6 f.show();
7 }

The null first argument instructs the method to use the default system
class loader. The second argument is the bean name.

Beans.instantiate() Methodology
The Beans.instantiate() method performs the following steps to
load a class and instantiate an object:

1. The bean name is initially treated as a serialized object name. The


name is appended with a .ser suffix and all dots are converted
to slashes. For example, sl291.GreenBean becomes
sl291/GreenBean.ser. The resource is then searched for in the
normal manner.

2. The default method for locating classes is employed by the class


loader, that is, it looks for a .class file in the CLASSPATH.

Persistence 6-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Recap of Persistence

Figure 6-2 summarizes the mechanisms used for persisting the state of
a bean through object serialization.

Writing to a Serialized Stream

String serFile = "filename.ser";


try {
FileOutputStream fileOStream = new
FileOutputStream(serFile);
ObjectOutputStream os = new
ObjectOutputStream(fileOStream);
os.writeObject(yourBeanObject);
os.close();
} catch (Exception e) {
e.printStackTrace();
}

Reading From a Serialized Stream


String serFile = "filename.ser";
try {
FileInputStream fileIStream = new
FileInputStream(serFile);
ObjectInputStream is = new
ObjectInputStream(fileIStream);
BeanType yourBeanRestored = (BeanType) is.readObject();
is.close();
} catch (Exception e) {
e.printStackTrace();
}

Figure 6-2 Recap of Persistence Mechanisms

6-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Exercise: Creating a New Bean Through Serialization

Exercise objective – The objective of this exercise is to create a new


bean using the serialization capabilities of the BeanBox.

Tasks

Creating a New Bean

1. Open the BeanBox.

2. Place a Molecule bean into the BeanBox. (Note that it defaults to


HyaluronicAcid.)

3. Switch the Molecule bean’s display to Benzene using the


property sheet.

4. Select SerializeComponent... from the File menu.

5. Call your new file benzene.ser and put it in the


SL291files/06-persist/get_started directory.

6. Quit the BeanBox and change to the get_started directory in


preparation for Module 6.

7. The manifest.tmp file in the directory you saved the serialized


bean to contains an entry for benzene.ser file. View the file to
see how to create a manifest file for a serialized bean.

Persistence 6-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Exercise: Creating a New Bean Through Serialization

Tasks

Creating a New Bean (Continued)

8. Execute the jar command below to create a new jar.

% jar cfm ben.jar manifest.tmp benzene.ser

9. Move your new jar file to the jars directory in the BDK
directory.

10. Launch the BeanBox and try out your new Benzene bean. Note
that it will now start out set to Benzene instead of
HyaluronicAcid.

6-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Exercise: Persisting the State of Your Beans

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

Persistence 6-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ What are the goals for bean storage?

❑ Describe how automatic Java serialization works.

❑ Using the serializable rules, what data fields should be marked as


transient and why?

❑ Describe the requirements to create persistent storage of objects.

❑ Add the mechanisms to persist a bean component.

6-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
6
Think Beyond

The BeanBox provides a PropertySheet window for use in modifying


the properties of a bean and a set of property editors are also
provided. Can you define your own property editor or property sheet?
Is there some other way to customize a bean?

Persistence 6-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Customization 7

Course Map
This module discusses how to augment the customization facilities of
your bean within the context of an application builder tool.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

7-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – The following questions are relevant to the topic of


customizing beans covered in this module:

1. When a developer loads your bean into a builder tool, what


common functionality for customizing the bean is available
regardless of the vendor?
✓ A builder examines the BeanInfo obtained through introspection, and provides a visual
panel (property sheet) of property descriptions and values. Optionally, it instantiates a
GUI-based customizer to allow a more flexible configuration of the bean.

2. As you selected properties on a bean’s property sheet (such as


font, color or boolean) for editing earlier in the course, you
interacted with different types of editors based on the variable
type. What if you had many beans that used a custom object as a
property? Could you augment any builder tool with a means to
support a special editor for your type?
✓ What a loaded question! Of course you can. The beans API provides a manager into which
you can install support for your own types of properties. For example, a Chart bean might
provide a pop-up list of chart types to choose from; or even better, a clickable gallery of
images for bar, line, pie, and other chart types to choose from.

7-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Objectives

Upon completion of this module, you will be able to:

● Identify the mechanisms provided in the JavaBeans API that


enable customization of a bean.

● Compare property sheets and property editors.

● Create a property editor for a specified property of a bean.

● Given a situation, evaluate the use of a customizer.

● Create a customizer for a bean component.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans API 1.0 Specification. [Online]. Available:


http://splash.javasoft.com/beans/spec.html.

● Sample code provided in the demo/sunw/demo directory of the


BDK.

Customization 7-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

What Can You Do Through Customization?

Customization provides a means for modifying the appearance and


behavior of a bean within an application builder so it meets your
specific needs. There are several levels of customization available for a
bean developer who wants other developers to get the maximum
benefit out of a bean’s potential functionality.

You can further understand the need for bean customization by


looking at what you have learned in earlier modules, and posing a few
questions to understand why it is not yet enough to meet the demands
of a large organization that plans to use beans.

7-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
What Can You Do Through Customization?

How Do Previous Modules Relate to Customization?


You saw how properties and events could be used within the BeanBox.
You learned how to specify your own properties and events for a bean.
In the Introspection module (Module 5), you examined the process
used to learn what can be changed about a bean, and how much
anyone, from users to bean developers to vendors who write
application builder tools, depend on naming conventions, BeanInfo
classes, and the like.

Property Sheets

Some of the changes made to beans so far have been fairly small,
atomic ones on common types. Recall the PropertySheet window used
in the BeanBox. The PropertySheet provides a text field to change
integers and strings. In addition, it provides slightly more
sophisticated GUI components such as choice boxes for Booleans that
can only be true or false. Even more complicated properties such as
Color and Font have their own pop-up GUI dialogs that coordinate a
few different controls. Figure 7-1 illustrates examples of these
properties on the BeanBox PropertySheet window.

String

Dialog window
(pop-up GUI)
Font

Boolean

Figure 7-1 Property Sheet Examples

Customization 7-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

What Can You Do Through Customization?

Can You Extend Editor Support to New Property Types?


Is this enough for a visual builder tool to provide for a large company
planning on building and integrating an increasingly complicated set
of beans into their future products? A company with specific needs
may deal with different types of complex objects as often as the Java
environment deals with color changes and font changes. Would a
company with these types of needs have to obtain a source license for
their favorite builder tool just to add support for types like Social
Security Number, Printer, or ServiceRequest? Certainly not! The
JavaBeans specification provides support for creating your own
property editors to handle other property types.

Property Editors

In this module, you will learn how simple it is to provide editors for
properties with a limited range of choices (similar to the true and false
choices provided for Boolean properties). Moreover, you will learn
how types such as Font and Color can have custom property editors
attached to them. This will enable you to create editors for your own
common object or property types.

7-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
What Can You Do Through Customization?

When Is a Property-Specific Editor Not Enough?


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.

Customizers

You will learn how a bean can provide support for customization
“wizards” that enter into a dialog with a user, providing a set of top-
level choices that lead to unique branches up a tree of choices for
configuring a bean.
✓ Remind the students of the Customize option that appears on the Edit menu when a bean
has a customizer class associated with it.

Customization 7-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Property Sheets and Property Editors

Property Sheets
A property sheet is a window that becomes visible for each bean that
is selected in a builder tool. The window consists of property name
and value pairs. A developer can visually manipulate each of a bean’s
public readable and writable properties through a PropertySheet
window.

As a customer evaluating the many visual application builder tools


designed for building and working with beans, you will observe that
each of them implements property sheets of some sort that resemble
the one provided by the BeanBox.

A builder constructs a property sheet at design time by providing a


displayable entry for each named property, along with an appropriate
representation of its value. Some properties are simple enough that
you can edit the property in a text field directly on the property sheet.
Other types require type-specific handling provided by a custom
property editor with a pop-up GUI.

7-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Property Sheets and Property Editors

Property Editors
When a property on a property sheet cannot be edited as a simple
textual string provided by the StringEditor property editor, you should
provide a custom property editor to handle modification of that
property’s type. In the BeanBox, a property editor is launched by
clicking on the property’s value.

The JavaBeans API provides methods for changing simple properties


in a predefined way. Most of the property types supported by the
BeanBox, including boolean, have editors implemented for them
using these methods. For others, such as Font and Color, the BeanBox
provides custom property editors that help a user configure a property
and provide the new property’s value as a result. No matter what the
editor, three different ways of viewing and making changes to the
property exist. The next section reviews how the BeanBox implements
viewing properties on the PropertySheet window before looking at the
default property editors provided by the API.

Customization 7-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Review of Views

Recall the discussion from Module 4, ‘‘Bean Properties,” of the views


used on the PropertySheet window. Based on the property editor
associated with a property (either your defined property editor or one
provided with the API), the PropertyCanvas, PropertySelector, or
PropertyText view is used. Figure 7-2 illustrates these various views as
used in the BeanBox.

OurButton Bean Properties

PropertyCanvas
views

PropertyText
views Dialog window

PropertySelector Molecule Bean properties


views

Figure 7-2 Views of the PropertySheet Window of the BeanBox

7-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

The PropertyEditor Interface

Description of the PropertyEditor Interface


The ProperyEditor interface is implemented by any class that wants
to provide editing support for a given type. PropertyEditor supports
a variety of ways to display and update property values. Most
property editors will only need to support a subset of the different
options available in this API, and may therefore find it more
convenient to extend the PropertyEditorSupport class.

Customization 7-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

The PropertyEditor Interface

How to Implement the PropertyEditor Interface


PropertyEditor implementations must follow certain policies to work
properly in a beans tool environment.

1. Every property editor must support one or more of the three


simple display styles:

a. Supports isPaintable().

b. Return a non-null String[] from getTags().

c. Return a non-null String from getAsText().

2. Every property editor must support a call on setValue() when


the argument object is of the type for which this is the
corresponding PropertyEditor.

3. Each property editor must either support a custom editor or


support setAsText().

4. Each property editor should have a default constructor.

7-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
The PropertyEditor Interface

Overview of the PropertyEditor Methods


Table 7-1 Important Methods Specified by the PropertyEditor

Method Description

getAsText() Gets the property value as a human editable


string.
getCustomEditor() Returns a full custom Component that edits
the property value. It is the responsibility of
the PropertyEditor to hook itself to its editor
Component and to report property value
changes by firing a PropertyChange event.
getJavaInitializationString() This method is intended for use when
generating Java code to set the value of the
property. It should return a fragment of Java
code that can be used to initialize a variable
with the current property value.
getTags() If the property value must be one of a set of
known tagged values, then this method
should return an array of the tags.
getValue() Returns the value of the property. The
return type is Object so primitive types must
be wrapped in the corresponding class type.
isPaintable() Returns true if the class will honor the
paintValue() method.
paintValue() Paint a representation of the value into a
given area of screen real estate.
setAsText() Set the property value by parsing a given
String.
setValue() Set (or change) the object that is to be edited
as the property value.
supportsCustomEditor() Returns true if the propertyEditor can
provide a custom editor.

Customization 7-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Creating Your Own Editor

As previously mentioned, if you have a more complex data type for


which there is no property editor registered with the
PropertyEditorManager, you might need to create your own editor.

There are actually two ways you can create your own property editor:

● Implement the PropertyEditor interface, defining the required


methods.

● Extend the utility class PropertyEditorSupport.

The ColorEditor and FontEditor implement the PropertyEditor


interface, and thus define each method specified by this interface.

7-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Creating Your Own Editor

Implementing the PropertyEditor Interface


You should implement the PropertyEditor interface when your bean
needs a custom editor on a new window. In your implementing class,
the default constructor should be written to create the GUI that will be
used to edit the property. The class should also contain methods for
event handling and sizing its GUI components.
✓ See the code for MultipleLine Label PropertyEditor which implements the PropertyEditor
interface. It is located at the end of this section.

Customization 7-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

PropertyEditor Requirements

Null Argument Constructor


Suppose you create a property editor called LabelEditor for a data type
MultiLineLabel. The code shown below demonstrates the use of a
null argument constructor for LabelEditor.
1 import java.beans.*;
2
3 public class LabelEditor implements PropertyEditor {
4
5 // Property editors must provide a default constructor. Strictly
6 // speaking, this constructor could have been generated by
7 // the compiler.
8 public LabelEditor() { }
9
10 . . .
11 }

7-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Please reinsert the new slide:

Supporting setValue()

PropertyEditor Requirements

Supporting setValue()
The setValue() method is used to modify a property of a bean. This
method must never modify the incoming object; instead, create a new
variable to reflect the modified version of the property. Cast the
incoming object argument (representing the property) to the
appropriate type (for example, cast to Color) and then set the variable
that represents the property to this value.
1 public class LabelEditor implements PropertyEditor {
2 String value;
3
4 public void setValue(Object value) {
5 value = (String)value;
6 }

Customization 7-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

PropertyEditor Requirements

Add and Remove PropertyChangeListeners


A bean editor that implements PropertyEditor must support the
addition and removal of a PropertyChangeListener. The standard
way to do this is illustrated in the code below.
1 private PropertyChangeSupport support =
2 new PropertyChangeSupport(this);
3
4 public void addPropertyChangeListener(PropertyChangeListener pl) {
5 support.addPropertyChangeListener(pl);
6 }
7
8 public void removePropertyChangeListener(PropertyChangeListener pl) {
9 support.removePropertyChangeListener(pl);
10 }

Note – The code shown here is the same as the code you used when
creating a bound property for a bean.

7-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Sample PropertyEditor for a MultipleLine Label

This PropertyEditor provides the ability to specify a label that spans


multiple lines. A new editor type is required since the BeanBox will
provide a simple TextField in the property sheet window. You need the
ability to specify multiple lines of text to be displayed.
1 package sl291.beans;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.beans.*;
6
7 public class LabelEditor implements PropertyEditor {
8 String value;
9
10 // Property editors must provide a default constructor.
11 public LabelEditor() { }
12
13 // Set (or change) the object that is to be edited. Built-in types
14 // such as "int" must be wrapped as the corresponding object type
15 // such as "java.lang.Integer".
16 public void setValue(Object value) { value = (String)value; }
17
18 // Return the value of the property.
19 public Object getValue() { return value; }
20
21 // Return true if the class will honor the paintValue method.
22 public boolean isPaintable() { return true; }
23
24 // Paint a representation of the value into a given area of screen
25 // real estate. Note that the propertyEditor is responsible for
26 // doing its own clipping so that it fits into the given rectangle.
27 public void paintValue(Graphics gfx, Rectangle box) {
28 gfx.setClip(box);
29 FontMetrics fm = gfx.getFontMetrics();
30 gfx.drawString("Click to edit...",
31 box.x + 5,
32 (box.y + box.height + fm.getAscent())/2);
33 }
34

Customization 7-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Sample PropertyEditor for a MultipleLine Label

35
36 // This method is intended for use when generating Java code to set
37 // the value of the property.
38 public String getJavaInitializationString() { return value; }
39
40 // Return the property value as a human editable string.
41 public String getAsText() { return value; }
42
43 // Set the property value by parsing a given String.
44 public void setAsText(String text) {
45 value = text;
46 }
47
48 // If the property value must be one of a set of known tagged
49 // values, then this method should return an array of the tags.
50 public String[] getTags() { return null; }
51
52 // A PropertyEditor may choose to make available a full custom
53 // Component that edits its property value.
54 public Component getCustomEditor() {
55 final TextArea labelArea = new TextArea(value);
56 labelArea.setSize(300, 150);
57 labelArea.addTextListener(new TextListener()
58 {
59 public void textValueChanged(TextEvent e) {
60 value = labelArea.getText();
61 listeners.firePropertyChange(null, null, null);
62 }
63 } );
64 return labelArea;
65 }
66
67 // Return true if the propertyEditor can provide a custom editor.
68 public boolean supportsCustomEditor() { return true; }
69

7-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Sample PropertyEditor for a MultipleLine Label

70 PropertyChangeSupport listeners = new


PropertyChangeSupport(this);
71
72 // Register a listener for the PropertyChange event.
73 public void addPropertyChangeListener(PropertyChangeListener pl) {
74 listeners.addPropertyChangeListener(pl);
75 }
76
77 // Remove a listener for the PropertyChange event.
78 public void removePropertyChangeListener
(PropertyChangeListener pl){
79 listeners.removePropertyChangeListener(pl);
80 }
81 }
82

Customization 7-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes

7-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Display Style Requirements

Editors implementing the PropertyEditor interface support a variety of


different options for displaying and updating property values. A
property editor must support one or more of the following three
display styles: graphic region display, text field display, or choice
component display.

● Graphic region display – Define the paintValue() method to


visually update a graphic region with a visual representing the
value of the property. The isPaintable() method returns true to
indicate this commitment, a true is also returned from
supportsCustomEditor(). The LabelEditor provides support for
a custom GUI component to change values.

Note – This corresponds to the PropertyCanvas view of the BeanBox


PropertySheet window on page 10.

✓ This option implies that getCustomEditor() returns a GUI component for editing the value
and for firing PropertyChange events (which is indicated by a true result from
supportsCustomEditor()). This is appropriate for property types that need more than a
simple TextField for editing values.

Customization 7-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Display Style Requirements

public boolean supportsCustomEditor() { return true; }

public Component getCustomEditor() {


final TextArea labelArea = new TextArea(value);
labelArea.setSize(300, 150);
labelArea.addTextListener(new TextListener()
{
public void textValueChanged(TextEvent e) {
value = labelArea.getText();
listeners.firePropertyChange(null, null, null);
}
});
return labelArea;
}

public void paintValue(Graphics gfx, Rectangle box) {


gfx.setClip(box);
FontMetrics fm = gfx.getFontMetrics();
gfx.drawString("Click to edit...",
box.x + 5,
(box.y + box.height + fm.getAscent())/2);
}

7-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Display Style Requirements

● Text field display – Return a non-null, editable String from


getAsText() representing the value, and support setAsText().
By extending PropertyEditorSupport, getAsText() is
automatically provided. An example that provides this type of
property editing is the BeanBox StringEditor class.

Note – This corresponds to the PropertyText view of the BeanBox


PropertySheet window on page 10.

1 package sun.beans.editors;
2
3 import java.beans.*;
4
5 public class StringEditor extends PropertyEditorSupport {
6
7 public String getJavaInitializationString() {
8 return "\"" + getValue() + "\"";
9 }
10
11 public void setAsText(String text) {
12 setValue(text);
13 }
14 }

Customization 7-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Display Style Requirements

● Choice component display – Return a non-null String[] from


getTags().

An example of this type of editor is illustrated by the BeanBox editor


for Boolean values: BoolEditor. An interesting feature of BoolEditor
is that it extends PropertyEditorSupport instead of directly
implementing PropertyEditor. This allows the class to override the
methods required to provide the needed functionality.

Note – This corresponds to the PropertySelector view of the BeanBox


PropertySheet window on page 10.

7-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Display Style Requirements

Sample Editor – BoolEditor


1 package sun.beans.editors;
2
3 // Property editor for a java built-in "boolean" type.
4
5 import java.beans.*;
6 public class BoolEditor extends PropertyEditorSupport {
7
8 public String getJavaInitializationString() {
9 // This must return local independent Java.
10 if (((Boolean)getValue()).booleanValue()) {
11 return ("true");
12 } else {
13 return ("false");
14 }
15 }
16 public String getAsText() {
17 if (((Boolean)getValue()).booleanValue()) {
18 return ("True");
19 } else {
20 return ("False");
21 }
22 }
23 public void setAsText(String text) {
24 if (text.toLowerCase().equals("true")) {
25 setValue(Boolean.TRUE);
26 } else if (text.toLowerCase().equals("false")) {
27 setValue(Boolean.FALSE);
28 } else {
29 throw new java.lang.IllegalArgumentException(text);
30 }
31 }
32 public String[] getTags() {
33 String result[] = { "True", "False" };
34 return result;
35 }
36 }

Customization 7-27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes

7-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Extending PropertyEditorSupport

As you have seen from previous modules, extending a provided


support class can be easier than implementing the respective interface.
The JavaBeans API provides a support class for the PropertyEditor
interface called PropertyEditorSupport.

When to Use
Use the utility class java.beans.PropertyEditorSupport when
your bean only needs to change a few methods defined by
PropertyEditorSupport,instead of defining all of the methods
required when implementing the PropertyEditor interface.

The following list contains examples of editors that extend


PropertyEditorSupport and a short description of the methods they
define:

● BoolEditor – Uses the Choice component display (PropertySelector


view) and defines the ensuing methods:

Customization 7-29
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Extending PropertyEditorSupport

When to Use (Continued)


▼ getTags() – Provides values “true” and “false” for a pop-up
list.

▼ setAsText() – Parses the String representation of the value


“true” or “false” and calls setValue() with the equivalent
Boolean value; getAsText() does the opposite.

▼ getJavaInitializationString() – Returns a string “true”


or “false” that can be used in Java code to set the value of a
property.

● StringEditor – Uses the text field display style (PropertyText view)


and defines the following methods:

▼ setAsText(String text) – Passes the string on to the


setValue() method.

▼ getJavaInitializatinString() – Builds a quoted string out


of the text returned from getValue() to return as a Java String.

● NumberEditor – Uses the text field display style and explicitly


defines the following method (uses get/setAsText() as defined
in the support class):

▼ getJavaInitializationString() – Returns getValue() cast


as a Java String.

7-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Making Your Property Editor Known

The PropertyEditorManager searches for a property editor by:

1. Looking to see if it is registered explicitly with a BeanInfo file.

2. Failing that, add “Editor” to the given Java data type and search
for the resulting dataTypeEditor. Packages are searched in the
following order:

a. Look for dataTypeEditor within the package directory of


the bean.

b. Failing that, look for dataTypeEditor in the list of editor


packages in the EditorSearchPath property. The default for
this is java.beans.editors.

c. Failing that, look for dataTypeEditor in a path provided by


the application builder.

Customization 7-31
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Making Your Property Editor Known

Naming Conventions
The name of your property editor should follow the naming
conventions of the JavaBeans API specification: dataTypeEditor.
However, if you have created an editor for a bean property with a data
type that already has an editor associated with it, such as String, then
you can name your editor after the property name. For example, the
MultiLineLabelBeanInfo uses the LabelEditor to change the
label property for the MultilineLabel bean. You must explicitly
register your editor using a BeanInfo file so that your editor will be
used for the property.

Note – Since it is difficult for you to know all of the editors that are
registered with the PropertyEditorManager, you might want to include
a BeanInfo file with your bean to explicitly register your property
editor as the one to use for a property of your bean.

7-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Making Your Property Editor Known

BeanInfo for the MultilineLabel Bean


The code for the corresponding BeanInfo file for the MultilineLabel
bean is shown here.
1 package sl291.beans;
2
3 import java.beans.*;
4 import java.awt.*;
5
6 public class MultilineLabelBeanInfo extends SimpleBeanInfo {
7 public BeanDescriptor getBeanDescriptor() {
8 return new BeanDescriptor(MultilineLabel.class);
9 }
10
11 PropertyDescriptor property(String name, String desc)
12 throws IntrospectionException
13 {
14 PropertyDescriptor p = new PropertyDescriptor(name,
15 MultilineLabel.class);
16 p.setShortDescription(desc);
17 return p;
18 }
19
20 public PropertyDescriptor[] getPropertyDescriptors() {
21 try {
22 PropertyDescriptor props[] = {
23 property("label", "The contents of the control"),
24 property("eolStyle",
25 "The method used to determine end of lines"),
26 property("alignment", "Where to align text"),
27 property("preferredWidth",
28 "The number of characters for width"),
29 property("font", "Font of label"),
30 property("background", "Background color of label"),
31 property("foreground", "Foreground color of label"),
32 property("name", "Name of component")
33 };
34
35 props[0].setPropertyEditorClass(LabelEditor.class);
36 props[1].setPropertyEditorClass(EolStyleEditor.class);
37 props[2].setPropertyEditorClass(AlignmentStyleEditor.class);

Customization 7-33
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Making Your Property Editor Known

BeanInfo for the MultilineLabel Bean (Continued)


38 return props;
39 } catch(IntrospectionException ex) {
40 ex.printStackTrace();
41 return super.getPropertyDescriptors();
42 }
43 }
44
45 public int getDefaultPropertyIndex() { return 0; }
46 }
47 }

7-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Recap of Property Editors

Figure 7-3 recaps what is necessary for creating your own property
editor.

Creating Your Own Property Editor

Extend PropertyEditorSupport Class

Decide what display style your editor will use

Define the appropriate methods for that display style: isPaintable(),


supportsCustomEditor(), getAsText(), setAsText(), or getTags().

Define a BeanInfo file to register your property editor, if necessary.

Implement PropertyEditor Interface

Provide a null argument constructor

Define the setValue(Object o) method.

Support the addition and removal of PropertyChangeListeners:

private PropertyChangeSupport support = new


PropertyChangeSupport(this);

public void addPropertyChangeListener(PropertyChangeListener pl){


support.addPropertyChangeListener(pl);
}

public void removePropertyChangeListener


(PropertyChangeListener pl) {
support.removePropertyChangeListener(pl);
}

Define the methods specified by the interface (some may be no-ops).

Figure 7-3 Recap of Creating Property Editors for a Bean

Customization 7-35
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor

Exercise objective – The objective of this exercise is to add a property


editor to an existing sl291.chart.Chart bean (provided for you) that
changes the Chart’s orientation from vertical to horizontal bars and
vice versa.

Preparation
To be prepared for this exercise, you should understand what methods
you need to define in a property editor to create a specific display style
on the PropertySheet window of the BeanBox.
✓ It is recommended that you stop the lecture at this point and have the students work on
creating their own property editor before moving on to customizers. Otherwise, students
become confused with what needs to be done in creating a property editor versus
creating a customizer.

7-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor

Tasks

Creating a Property Editor

1. Change to the SL291files/work directory.

2. Create a JAR file for the Chart bean by typing the following
command:
% jam -sjf=chart.jam

3. Load the chart.jar file into the BeanBox using File ➤ Loadjar
or by restarting the BeanBox.

4. Create an instance of the Chart bean and become familiar with its
properties and how changing them affects the Chart bean.

5. Modify the ChartBeanInfo class that describes a


ChartOrientationEditor class as a property editor for the
“orientation” property. (You can also use BeanInfo to limit the
number of properties that are displayed in the PropertySheet
window of the BeanBox.)

6. Create the ChartOrientationEditor class according to the


following steps (referring to the code for the BoolEditor on page
29 may be helpful):

a. Implement a getTags() that returns “horizontal” or


“vertical”.

b. Implement a getJavaInitializationString() that returns


“1” for “horizontal” and “0” for “vertical.

c. Implement setAsText() to call setValue() with the


appropriate integer, or throw IllegalArgumentException.

d. Implement getAsText() to return the string values.

Customization 7-37
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor

Tasks

Testing in the BeanBox

1. Remake chart.jam to include the new BeanInfo file and


property editor for the Chart bean.

2. Reload the JAR file into the BeanBox using File ➤ Loadjar or by
restarting the BeanBox.

3. Create an instance of the new Chart bean in the BeanBox.

4. Toggle between orientations using the property editor you


created (that is now displayed on the PropertySheet window of
the BeanBox) and watch the chart orientation change.

7-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Property Editor

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their work place.

Customization 7-39
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Notes

7-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Customizers

Recall that customizers are used typically to create “wizard”-like


functionality. They can provide a higher level of bean customization
than is usually available through property editors. Customizers differ
most significantly from property editors when they lead the developer
through a decision tree to configure many properties.

Customizer Use
Customizers are used at design time, and often result in a bean that
can be saved in a serialized state to make a new bean. Use a
customizer when the configuration you want to do to a bean is
impossible with the property editor mechanism. For instance, a
customizer can easily display a graphical implementation of what can
be changed. So, for example, you could have a customizer that
displays a model of a car, enabling you to change the whole system
rather than wheel type, engine size, sport versus utility, and so on.

Customization 7-41
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Customizers

Characteristics of Customizers
The following characterize a customizer for a bean:

● A customizer changes a property without destroying and re-


creating it. This characteristic is in contrast to a property editor
which must submit a new object that reflects any changes.
✓ A customizer should update often the target bean’s screen appearance, even if it batches
changes and applies them to the bean at various points.

✓ This could mean that each change done affects the bean, and are backed out if the user
does something equivalent to a cancel on the customizer, it could mean that a new
version of the bean is customized and an apply applies it to the current in-design version,
or it could mean no changes occur until apply.

● A customizer class must notify PropertyChangeListeners of


property changes. In so doing, a customizer changes the state of all
properties that are present on the property sheet so they do not get
out of sync.

● A customizer may choose to include property editors in its screen


appearance to edit target data values, or it may have its own
methods.

● A bean with a customizer will also have a BeanInfo file.

Naming Conventions
Your customizer should be named using the naming convention
BeanNameCustomizer. So, for example, a bean called Chart would
have a customizer called ChartCustomizer defined in
ChartCustomizer.java.
✓ This naming convention is not a requirement. In fact, there is no evidence that the
Introspector or a builder tool looks for this convention. The getCustomizer() method is
used to return the actual object.

7-42 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Implementing a Customizer Class

Implementation Requirements
The following are required to implement a customizer for a bean:

● Define a BeanInfo file

● Extend java.awt.Component or a subclass

● Implement the Customizer interface

● Provide a null argument constructor for the customizer

● Support the addition and removal of a PropertyChangeListener (as


done by property editors)

● Define the setObject(Object bean) method

In addition, customizers can implement event listeners and other


necessary events. Most customizers will have many other methods,
such as getPreferredSize() which are specific to the particular
component they extend.

Customization 7-43
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Implementing a Customizer Class

Defining BeanInfo
A bean with a customizer must have a BeanInfo file defined for it so
builder tools can locate the beans customizer class. The BeanInfo file
specifies the customizer class as shown in the following code:
1 import java.beans.*;
2
3 public class MyBeanBeanInfo extends SimpleBeanInfo() {
4 public BeanDescriptor getBeanDescriptor() {
5 return new BeanDescriptor(MyBean.class, MyBeanCustomizer.class);
6 }
7 }

7-44 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Implementing a Customizer Class

Extending Component/Implementing Customizer


Your customizer must extend the Component class or any of its
subclasses (this is so it can be instantiated inside an AWT dialog or
panel), as well as implement the Customizer interface.

Providing a Null Argument Constructor


Define a null argument constructor for your bean customizer. Any
initial code used to create and configure the customizer class is
included in the constructor.
1 import java.beans.*;
2
3 public class MyBeanCustomizer extends Panel implements Customizer {
4 public MyBeanCustomizer() {
5 // Code to build and add GUI of the customizer
6 }
7 // All the other methods and code...
8 }

Customization 7-45
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Implementing a Customizer Class

Adding and Removing PropertyChangeListeners


As you did for property editors, your customizer must provide
methods for registering PropertyChangeListeners. The standard
way of supporting this is illustrated in the code below.
1 // In the most common case the support can be set globally this way.
2 private PropertyChangeSupport support =
3 new PropertyChangeSupport(this);
4
5 public void addPropertyChangeListener(PropertyChangeListener pl) {
6 support.addPropertyChangeListener(pl);
7 }
8
9 public void removePropertyChangeListener(PropertyChangeListener pl) {
10 support.removePropertyChangeListener(pl);
11 }

7-46 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

Implementing a Customizer Class

Defining setObject()
The setObject() method is called only once before your customizer
has been added to any parent AWT container. Within the
setObject() method, the argument passed to setObject() is cast to
the bean type and saved to a variable of the bean type (similar to what
is done in the setValue() method for property editors).
1 private MyBean bean;
2 public void setObject(Object beanToCustomize) {
3 bean = (MyBean) beanToCustomize;
4 // Code to get current properties for "bean" and/or
5 // Code to build GUI elements for customizer and add them to layout.
6 }

Customization 7-47
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Example of a Customizer

The BDK provides several beans that have customizers: JDBC SELECT,
BridgeTester, and OurButton beans. The code below is from the
OurButtonCustomizer class.
1 package sunw.demo.buttons;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.beans.*;
6
7 public class OurButtonCustomizer extends Panel
8 implements Customizer, KeyListener
9 {
10 public OurButtonCustomizer() {
11 setLayout(null);
12 }
13
14 public void setObject(Object obj) {
15 target = (OurButton) obj;
16
17 Label t1 = new Label("Caption:", Label.RIGHT);
18 add(t1);
19 t1.setBounds(10, 5, 60, 30);
20
21 labelField = new TextField(target.getLabel(), 20);
22 add(labelField);
23 labelField.setBounds(80, 5, 100, 30);
24
25 labelField.addKeyListener(this);
26 }
27
28 public Dimension getPreferredSize() {
29 return new Dimension(200, 40);
30 }
31
32 /**
33 * @deprecated provided for backward compatibility with old layout
34 * managers.
35 */
36 public Dimension preferredSize() {
37 return getPreferredSize();
38 }
39

7-48 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Example of a Customizer

40 public void keyTyped(KeyEvent e) {


41 String txt = labelField.getText();
42 target.setLabel(txt);
43 support.firePropertyChange("", null, null); // there’s only one
44 }
45
46 public void keyPressed(KeyEvent e) { }
47
48 public void keyReleased(KeyEvent e) { }
49
50 public void addPropertyChangeListener(PropertyChangeListener pl) {
51 support.addPropertyChangeListener(pl);
52 }
53
54 public void removePropertyChangeListener(PropertyChangeListener pl){
55 support.removePropertyChangeListener(pl);
56 }
57
58 private PropertyChangeSupport support = new
59 PropertyChangeSupport(this);
60 private OurButton target;
61 private TextField labelField;
62 }

Customization 7-49
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Recap of Customizers

Figure 7-4 recaps what is required for creating a customizer for a bean.

Creating a Customizer Class

Define a BeanInfo file


public class MyBeanBeanInfo extends SimpleBeanInfo() {
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(MyBean.class, MyBeanCustomizer.class);
}
}

Extend java.awt.Component or a subclass and implement the Customizer interface


public class MyBeanCustomizer extends Panel implements Customizer {

Provide a null argument constructor for the customizer


public MyBeanCustomizer() {
//code here
}

Support the addition and removal of a PropertyChangeListener

private PropertyChangeSupport support = new


PropertyChangeSupport(this);

public void addPropertyChangeListener(PropertyChangeListener pl) {


support.addPropertyChangeListener(pl);
}

public void removePropertyChangeListener(PropertyChangeListener pl) {


support.removePropertyChangeListener(pl);
}

Define the setObject(Object bean) method


public void setObject(Object beanToCustomize) {
private MyBean bean = (MyBean) beanToCustomize;
// remaining code here
}
Figure 7-4 Recap of Creating a Customizer for a Bean

7-50 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Customizer

Exercise objective – The objective of this exercise is to add a


ChartCustomizer to complement the property editor you wrote. For
educational purposes, the customizer will enable designers to modify
the chart type property between “bar” and “column” chart types. This
effectively changes the orientation of the chart between horizontal and
vertical.

Preparation
To be prepared for this exercise, you should have completed the
exercise for writing the code for your ChartOrientationEditor. If
you did not have time to finish that exercise, use the solutions
provided for this module to complete your code before beginning this
lab exercise.

Customization 7-51
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Customizer

Tasks

Creating a Customizer

1. Create a ChartCustomizer class that is a panel with its own GUI


for selecting between “bar” and “column.”

2. Add support for the customizer in the BeanInfo class for the
Chart bean.

3. For the first coding pass, implement the customizer functionality


by invoking the setChartType() Chart method each time the
user changes the chart type. For example, if the user is presented
a choice for selecting the chart type, call the SetChartType()
method each time an ItemEvent event is generated.

For a more robust solution, fire a property change event


whenever the user changes the chart type using the customizer.

Testing in the BeanBox

1. Compile and reload the JAR file into the BeanBox.

2. Modify the chart type using your customizer and make changes
to the Chart bean using your existing orientation editor. See how
the customizer and property editor interact.

7-52 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Exercise: Creating a Customizer

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspect of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their work place.

Customization 7-53
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ What mechanisms are provided in the JavaBeans API that enable


customization of a bean?

❑ Compare property sheets and property editors.

❑ Create a property editor for a specified property of a bean.

❑ Describe a situation where it would be beneficial to use a


customizer for a bean.

❑ Create a customizer for a bean component.

7-54 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7
Think Beyond

The next module on adaptors addresses some of the issues that can
occur when trying to handle events that an object has registered for.
For instance, if you register with several components that send
ActionEvents, how do you determine which component the
ActionEvent originated from? What about the case where an event
source has several interested objects that want tailored information
from the event sent by the source?

Customization 7-55
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
7

7-56 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Event Adapters 8

Course Map
This module discusses event adapters—what they are and how they
can be used to add an event delivery policy between sources and
listeners.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

8-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – The answers to the following questions are of interest to


the topic of event adapters discussed in this modules.

1. What is the code that is generated by builder tools when you


hook one Bean to another? What does it do?

✓ The code generated by builder tools is actually an adapter class. It sits between the
source of the event and the object interested in the event. It receives the event from the
source and forwards that event to the targeted method of the “listener” object. This code
is necessary because a builder tool does not know what Beans you plan to hook together
through events. The builder tool must dynamically generate this code to make the Beans
work together as one application.

2. Since listeners can only implement a particular listener interface


once, and it is possible to register as a listener with multiple
sources that fire the same event type, do listeners need to write
the code that determines what source an event came from? Can
this “code-analysis” be done outside the listener?
✓ Listeners do not have to determine for themselves which source generated an event. A
class can be defined that receives the event from the source, does the analysis and
decision-making, and then forwards the event on to an appropriate method of the listener.
This scenario has advantages in GUI applications because it is possible to separate the
application logic from the GUI itself. This separation enables a programmer to modify the
GUI without changing the application-specific code.

8-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Objectives

Upon completion of this module, you will be able to:

● Define event adapter.

● Compare multiplexing and demultiplexing adapters.

● Justify the use of event adapters.

● Differentiate an event adapter from an event listener.

● Write an event adapter for a Bean component.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans API 1.0 Specification. [On-line]. Available:


http://splash.javasoft.com/beans/spec.html.

● Java AWT: Delegation Event Model. [Online]. Available:


http://www.javasoft.com:80/products/jdk/1.1/docs/
guide/awt/designspec/events.html.

Event Adapters 8-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
What Is an Event Adapter?

An event adapter is an object that interposes between event sources and


event listeners to provide added control over event delivery. An
adapter will implement the XXXListener interface required by a
source for the event the source fires. It then receives the event
notifications from the source, makes some decisions based on the
event, and then passes the event on to a specific method of an
interested object.

Event
source
Interested
object
Fires (“listener”)

XXXEvent
XXXEvent

Event
adapter
(implements
XXXListener
interface; does
decision-making)

Figure 8-1 Event Adapter Overview

8-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Adapters Used in the BeanBox

When you connect two Beans in the BeanBox using the Edit ➤ Events
submenu, a hookup class is created in the beanbox/tmp/sun/beanbox
directory. Each hookup class is actually an event adapter. It
implements a listener interface and defines the handler method
specified by that interface.

Event Adapters 8-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Adapters Used in the BeanBox

Example of an Adapter Hookup Class


The code created for a typical hookup class looks like the following:
1 // Automatically generated event hookup file.
2
3 package tmp.sun.beanbox;
4
5 public class ___Hookup_13fdc34850 implements
6 java.awt.event.ActionListener, java.io.Serializable {
7
8 public void setTarget(sl291.choice.MyChoice t) {
9 target = t;
10 }
11
12 public void actionPerformed(java.awt.event.ActionEvent arg0) {
13 target.addRemoveItem(arg0);
14 }
15
16 private sl291.choice.MyChoice target;
17 }

8-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Adapters Used in the BeanBox

Example of an Adapter Hookup Class (Continued)


✓ In the case of the BeanBox, the target Bean (considered the interested object) does not
register the adapter with the source since the adapter is created dynamically during the
running of the BeanBox. The HookupManager class does this registration using the
following code:

args[0] = hookup;
esd.getAddListenerMethod().invoke(source, args);
where esd is an EventSetDescriptor object.

✓ The invoke method is defined in Method.java in java.lang.reflect. It invokes the


underlying method represented by this Method object on the specified object with the
specified parameters. Hence, in the code above, the addXXXListener method of the source
Bean is called to register the hookup class (adapter) as a listener.

You might recognize some of the code shown here. This hookup class
was generated when the MyChoice Bean was chosen as the target of
the ActionEvent generated by the MyButton Bean. This adapter
implements the ActionListener interface and defines the required
handler method actionPerformed.

The actionPerformed method merely passes the ActionEvent on to


the chosen target method (the method you selected from the
EventTargetDialog window). In this hookup class, this target method
is addRemoveItem.

Event Adapters 8-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Types of Adapters

There are two types of adapters discussed in the JavaBeans


specification:
✓ The definitions here were confirmed by Larry Cable of JavaSoft engineering.

● Demultiplexing adapter – Adapter receives events from many


sources and through some decision-making logic, forwards the
events to the appropriate method of a single object.

● Multiplexing adapter – Adapter receives events from a single source


and through some decision-making logic, forwards the events to
one object selected from many possible objects.

You will create a multiplexing adapter in the lab exercises.

8-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Types of Adapters

Common Uses of Adapters


The BeanBox illustrates one common use of event adapters—acting as
a generic hookup between sources and what would normally be the
listeners.

Other uses of adapters include the following:

● Implementing an event queue between sources and “listeners” to


provide more control over delivery of events

● Acting as a filter

● Receiving events from multiple sources and determining the


appropriate method to call in a single event “listener”

With regard to this last case, consider an object that implements


the ActionListener interface, but registers itself with several
different buttons, a text field, and possibly a list. Each can fire an
ActionEvent. In this situation, the listener must determine
where the event originated. However, adding an adapter
between the source and the listener removes this decision-
making from the listener.
✓ Stress the advantages adapters can provide, implementations such as removing the
decision-making logic from Beans, separating GUI components from the logic code,
tailoring event information to specific Bean types, and so forth.

Event Adapters 8-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Types of Adapters

Diagrams
Figure 8-2 gives a conceptual overview of how demultiplexing and
multiplexing adapters function.

Event
source1 Fire
event
Forward
Event Fire Demultiplexing event Interested
source2 event adapter or call object
specific
method
Event Fire
source3 event

Interested
Fire object
event

Event Fire Multiplexing


source event Fire Interested
adapter event object

Fire
event Interested
object

Figure 8-2 Demultiplexing and Multiplexing Adapters

8-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Notes

Event Adapters 8-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Differentiating Adapters From Normal Listeners

What distinguishes an event adapter from the event listeners you are
familiar with from previous modules?

Case With No Adapters


In the case where you do not have adapters, just sources and listeners,
the listener does the following:

● Implements the XXXListener interface expected by the event


source.

● Defines the event handling method specified by the XXXListener


interface.

● Registers itself as a listener with the event source using the


addXXXListener method of the event source.

8-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Differentiating Adapters From Normal Listeners

Case With Adapters


In the case where you have an event adapter, what would normally be
the listener becomes an interested object that is interested in the
XXXEvent. The event adapter does the following:

● Implements the XXXListener interface expected by the event


source.

● Defines the event-handling method specified by the XXXListener


interface.

● Defines some logic to decide which interested object to forward


the event to, or which method of an interested object should be
called.

The interested object usually registers the adapter as a listener using


the addXXXListener method of the event source. However, builder
tools and the BeanBox take care of this registration for you (which they
should because your Bean does not know what other Bean it might be
hooked up to).

Event Adapters 8-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Demultiplexing Adapter Example

Application Window
Consider the many window applications you have used in the past.
Common buttons include Apply, Reset, Save Changes, Cancel, and
Quit. To illustrate a demultiplexing adapter, assume you are writing an
application that includes two buttons (Apply and Quit) and a List. The
application is shown in Figure 8-3.

Figure 8-3 Application Example That Uses a Demultiplexing


Adapter

8-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Demultiplexing Adapter Example

Description of Application
There are three source files for this application: Appl.java,
Widgets.java, and ActionAdapter.java.

● Appl.java – The main application defines the methods associated


with each GUI component (widget).

● Widgets.java – The Widgets class builds the components or


widgets.

● ActionAdapter.java – The adapter receives action events and


decides which method in the main application to call.

Event Adapters 8-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Demultiplexing Adapter Example

Appl.java Code
The code below is used in the main application.
1
2 // An application that creates a Frame with several widgets that
3 // each generate an ActionEvent
4 // The ActionEvent is fired to the ActionAdapter, which decides
5 // what widget the event originated, and calls an appropriate method
6
7 public class Appl {
8 public Widgets wid;
9
10 static public void main(String args[]) {
11 Appl app = new Appl();
12 app.wid = new Widgets(app);
13 }
14
15 public void apply() {
16 System.out.println("Do apply ...");
17 }
18
19 public void quit() {
20 System.out.println("Quitting...");
21 }
22
23 public void doFonts() {
24 System.out.println("put up Fonts dialog");
25 }
26
27 public void doColor() {
28 System.out.println("put up Color dialog");
29 }
30
31 public void doPatterns() {
32 System.out.println("put up Patterns dialog");
33 }
34 }

8-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Demultiplexing Adapter Example

Widgets.java Code
The code below defines the button and list widgets for the application
and registers an adapter as the listener for each.
1 import java.awt.*;
2 import java.awt.event.*;
3
4 // Create the Widgets for this application
5 // and register the adapter as the listener for each
6
7 public class Widgets {
8 Button apply, quit;
9 List myList;
10
11 public Widgets(Appl app) {
12 Frame f = new Frame("My Widgets");
13 f.setLayout(new FlowLayout());
14 ActionAdapter adapt = new ActionAdapter(app);
15
16 //Build the widgets
17 apply = new Button("Apply");
18 quit = new Button("Quit");
19 myList = new List();
20 myList.add("Fonts");
21 myList.add("Color");
22 myList.add("Patterns");
23
24 f.add(apply);
25 f.add(quit);
26 f.add(myList);
27
28 // add adapter as listener for buttons, list
29 apply.addActionListener(adapt);
30 quit.addActionListener(adapt);
31 myList.addActionListener(adapt);
32
33 //put up Frame
34 f.pack();
35 f.setVisible(true);
36 }
37 }

Event Adapters 8-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Demultiplexing Adapter Example

ActionAdapter.java Code
Below is the code for the demultiplexing adapter which decides what
method should be called based on the information that it receives.
1 import java.awt.event.*;
2
3 // The demultiplexing adapter that receives ActionEvents from
4 // several sources, determines which type source sent the event
5 // and calls the appropriate method
6
7 public class ActionAdapter implements ActionListener {
8 private Appl app;
9
10 public ActionAdapter(Appl app) {
11 this.app = app;
12 }
13
14 public void actionPerformed(ActionEvent evt) {
15 Object x = evt.getSource();
16 if (x == app.wid.apply)
17 app.apply();
18 else if (x == app.wid.quit)
19 app.quit();
20 else if (x == app.wid.myList){
21 int index = app.wid.myList.getSelectedIndex();
22 if (index == 0)
23 app.doFonts();
24 else if (index == 1)
25 app.doColor();
26 else if (index == 2)
27 app.doPatterns();
28 else
29 return;
30 } else
31 // Unidentified source
32 System.out.println("Error: widget item not recognized");
33 }
34 }

8-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Notes

✓ The course_examples directory for this module includes the code presented here in the
directory OneAdapter. There is also a directory called ManyAdapters which takes this same
code and modifies it slightly so that each widget registers its own particular adapter.

✓ Note that with the code used in the adapter, there is no tie to the actual string names on
the Widgets. Thus, the code in the adapter can be used even if the Widgets class changes
its strings for the component labels to strings in another language.

✓ You might describe for the students what the code would look like without the adapter and
what restraints or issues that might raise. For instance, without the adapter, the Widgets
class would have to determine where the ActionEvent originates by itself. The widgets are
no longer separated from the logic of the application.

Event Adapters 8-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8

Multiplexing Adapters

Overview of Multiplexer Exercise


In the exercise you will create a multiplexing adapter that:

● Receives a DataEvent event (which you will define).

● Generates a DataTableEvent event (which you defined in a


previous exercise) from the information in the DataEvent.

You are provided with an AdapterButton Bean that will generate and
fire the DataEvent events with test data to the multiplexing adapter
that you create.

8-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Multiplexing Adapters

Overview of Multiplexer Exercise (Continued)


From the information in the DataEvent, the adapter constructs a
DataTableEvent tailored to each of three possible DataTableBeans:

● An XAxis DataTableBean (the number of rows is 1).

● A YAxis DataTableBean (the number of columns is 1).

● A table DataTableBean (neither the number of rows nor columns


is 1).

If any one of the above types of Beans is registered as a listener on the


adapter, it receives a DataTableEvent tailored for it and populates its
table cells with the information it receives.

Event Adapters 8-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Multiplexing Adapters

Overview of Multiplexer Exercise (Continued)


Figure 8-4 illustrates the instances of these Beans in the BeanBox.

Test button
fires DataEvent
to adapter YAxis
DataTableBean

Multiplexing
adapter generates
DataTableEvents and
fires it to XAxis
DataTableBeans DataTableBean

Table
DataTableBean

Figure 8-4 Multiplexing Adapter Overview

8-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Exercise objective – The objective of this exercise is to create a


multiplexing event adapter that controls the delivery of an event to
one of three DataTableBean Beans. You will test this adapter with a
special button Bean that is provided. In the next module, “Distributed
Computing With Beans,” you will replace the button Bean with an
RMI Bean.

Preparation
This exercise builds on the work done in previous exercises with the
DataTableBean, DataTableEvent, and DataTableListener classes.
Be sure you have completed code from previous exercises for these
classes, or use the solutions provided in those exercises to finish your
code for use in this exercise.
✓ It might be helpful (and save time) to walk through all of the steps that describe what the
students are supposed to code to make sure they understand what they will be doing.

Event Adapters 8-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Creating the Adapter

In this exercise, you will create a DataEventMultiplexer Bean that is


hooked up to various Beans as illustrated in Figure 8-5.

AdapterButton
DataTableBean
(Table)
ent
Fires DataEvent
e Ev
abl
t aT
DataTableBean
Da
b leEvent (XAxis)
DataTa
DataEventMultiplexer
Data
Tabl
eEve DataTableBean
nt
(YAxis)

Figure 8-5 Bean Hookup for Adapter Lab

1. Change to the SL291files/work directory.

2. Create a directory called dataEvent.

8-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Creating the Adapter (Continued)

3. Define a new event called DataEvent that:


✓ Remind the students that DataEvent must extend java.util.EventObject, otherwise the
introspection process does not display the correct events for the Bean.

▼ Defines the following data members:


● private String [][] data;
● private String [] xAxis;
● private String [] yAxis;
● private String ID, xLabel, yLabel;

▼ Defines a constructor with one argument which is the source


component.

▼ Defines get and set methods for each of the private data
members.

4. Create a DataEventListener interface with an event handling


method called fireDataEvent(DataEvent de).
✓ Remind the students that DataEventListener must extend java.util.EventListener so
that the introspection process can build the Edit ➤ Events menu correctly.

5. Create a multiplexing adapter called DataEventMultiplexer


that:

▼ Extends Panel and implements the DataEventListener


interface.

▼ Defines a no argument constructor that puts a label on the


panel indicating it is a multiplexer.

▼ Defines variables to indicate whether you have main table,


XAxis, or YAxis DataTableBeans registered as listeners.

▼ Initializes the variables to null.

Event Adapters 8-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Creating the Adapter (Continued)

▼ Defines itself as a unicast source for XAxisListeners,


YAxisListeners, and DataTableListeners (that is, defines
add/remove methods for each of these, each of which takes its
own type of listener as an argument; the add methods throw
TooManyListenersException if there already is a listener of
that type).

Note – The use of a unicast source is instructional. For this exercise,


you only want one DataTableBean of any of the three types registered
at a time.

Example of an add method:

1 public void addXAxisListener (DataTableListener dtl)


2 throws TooManyListenersException {
3 if (xListener != null) {
4 throw new TooManyListenersException ();
5 }
6 xListener = dtl;
7 }
▼ Defines the fireDataEvent handler method required by the
DataEventListener interface. The fireDataEvent() method
constructs an appropriate DataTableEvent for each
DataTableBean listener registered.

For example, if xListener is not null, the multiplexer creates a


DataTableEvent using the getXAxis() method to obtain the
data for the DataTableEvent. The DataTableEvent is then
sent to the listener by calling its fireDataTableEvent method.

8-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Creating the JAR files and Instantiating Your Beans

1. Change to the SL291files/work directory.

2. Use the jam command to create the JAR files for your new Beans.

3. Restart the BeanBox.

4. Create instances of the AdapterButton, DataEventMultiplexer,


and three DataTableBeans. Use the PropertySheet window to:

▼ Make one DataTableBean a 1xN table (XAxis DataTableBean).

▼ Make another DataTableBean a Nx1 table (YAxis


DataTableBean).

▼ Make sure the third DataTableBean has more than one row
and more than one column.

Event Adapters 8-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Hooking the Beans Together for Testing

1. Select the AdapterButton and choose


Edit ➤ Events ➤ dataEvent ➤ fireDataEvent.

2. Connect the red rubberbanding line to the


DataEventMultiplexer and choose fireDataEvent from the
EventTargetDialog window.

3. With the DataEventMultiplexer selected, choose


Edit ➤ Events ➤ dataTable ➤ fireDataTableEvent.

4. Connect the red rubberbanding line to the DataTableBean with


the number of rows and columns greater than 1 and choose
fireDataTableEvent from the EventTargetDialog window.

5. Select the multiplexer again and choose


Edit ➤ Events ➤ XAxis ➤ fireDataTableEvent.

6. Connect the red rubberbanding line to the DataTableBean with


the number of rows equal to 1 and choose fireDataTableEvent
from the EventTargetDialog window.

7. Select the multiplexer again and choose


Edit ➤ Events ➤ YAxis ➤ fireDataTableEvent.

8. Connect the red rubberbanding line to the DataTableBean with


the number of columns equal to 1 and choose fireDataTableEvent
from the EventTargetDialog window.

8-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Tasks

Hooking the Beans Together for Testing (Continued)

Figure 8-6 illustrates the different DataTableBeans after they receive


data and resize themselves.

XAxis

Main table
YAxis

Figure 8-6 Resulting DataTableBeans After Being Populated


With Data

Event Adapters 8-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Exercise: Working With Adapters

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” You might find you do not have time to spend on discussion.
Then just highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

8-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Define event adapter.

❑ Compare multiplexing and demultiplexing adapters.

❑ What are common uses of event adapters?

❑ Differentiate an event adapter from an event listener.

❑ Write an event adapter for a Bean component.


✓ You might ask students the following question to check their understanding up to this
point: In the exercise when you looked at the Edit ➤ Events submenu, you saw entries for
XAxis, dataTable, and YAxis (all of which show fireDataEvent on their submenus). How did
these get added to the menu?

Answer: The multiplexer is a source for DataTable, YAxis, and XAxis listeners, so it
defined the registration methods addXXXListener and removeXXXListener. The
introspection process found these add/remove methods for listeners and generated
the appropriate menu items.

Event Adapters 8-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
8
Think Beyond

How can Beans be used in a distributed systems? Can Beans be used


as intelligent front-ends that interface with network servers? How
might this work with RMI, JDBC, and JavaIDL APIs from JavaSoft?

8-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Distributed Computing
With Beans 9

Course Map
This module provides an overview of the role JavaBeans components
play in a distributed computing environment.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

9-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Relevance

Discussion – The World Wide Web (WWW) has impacted companies


and individuals alike. The use of intranets and the Internet continue to
grow at a rate unthought of a decade ago. The number of applications
that run in a distributed network environment is also increasing. How
do JavaBeans components fit into the realm of distributed computing
applications? What network access mechanisms are available?
✓ Developing a software component that interacts with other components or applications
over the network would need to consider the slower speeds of the network, as well as
recovery and re-synchronization mechanisms for component or machine failure.
Therefore, most component models do not try to integrate all the requirements of
heterogeneous networked computing environments. Rather, they leverage established
distributed computing technologies.

JavaBeans components can be designed to act as intelligent front ends for network
servers by leveraging the network access mechanisms provided by JavaSoft (Java
DataBase Connectivity API (JDBC), Java Remote Method Invocation (Java RMI), and Java
IDL) or leveraging other distributed computing mechanisms.

✓ Note:

• The intent of this module is not to teach students how to write JDBC, RMI, or JavaIDL
applications (in fact, they will not be able to do so after taking this module), but rather
to show them how these JavaSoft distributed programming technologies can be used
with beans.

• For those students interested in learning how to program in these APIs, refer them to
the SL-301 course, Distributed Programming With Java.

9-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Objectives

Upon completion of this module, you will be able to:

● Describe, in one paragraph, the JDBC architecture.

● Describe how a bean component works with JDBC.

● Describe, in one paragraph, the Java RMI architecture.

● Explain how to implement a Java RMI bean.

● Create bean components to be used on the client side of a Java


RMI application.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● “The Java Remote Method Invocation Specification.” [On-line].


Available: http://chatsubo.javasoft.com/current/doc/
rmi-spec/rmi-spec.ps and
http://www.javasoft.com:80/products/jdk/1.1/docs/
guide/rmi/index.html.

● “Java RMI Tutorial.” [On-line]. Available:


http://chatsubo.javasoft.com/current/doc/tutorial/
rmi-getstart.ps.

● Java IDL. [Web pages]. Available:


http://splash.javasoft.com/JavaIDL/pages/index.html.

● The JDBC.™ [Database Access API]. Available:


http://splash.javasoft.com/jdbc/.

● Orfali, Harkey, and Edwards. The Essential Distributed Objects


Survival Guide. (John Wiley & Sons, Inc. 1996).

Distributed Computing With Beans 9-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

Motivating Scenarios for Distributed Bean Programming

What sort of beans can be developed within the realm of distributed


computing?

Areas of Familiarity
A developer who needs to be able to answer this question should have
some understanding of the following:

● The facilities that the Java programming language provides, such


as its rich object-oriented structure, that are used to implement a
well-designed distributed object framework.

● RMI for distributed Java-to-Java connectivity or JavaIDL for


heterogeneous connectivity (Java to non-Java) using CORBA and
Internet-Inter ORB Protocol (IIOP).
✓ ORB is object request broker; CORBA is common object request broker architecture.

9-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Motivating Scenarios for Distributed Bean Programming

Areas of Familiarity (Continued)


● The architecture options available for distributed object solutions,
which would allow a homegrown solution to be created from
scratch.

● A few of the technologies available for enterprise services and


transactions, such as:

▼ Java DataBase Connectivity (JDBC) – For SQL–type database


queries.

▼ Java Naming and Directory Interface (JNDI) – A rigorous


naming service for resources; this often involves a standard
protocol or service such as Lightweight Directory Access
Protocol (LDAP), Novell Directory Services (NDS), Domain
Name System (DNS), or Network Information Service (NIS).

▼ Java Commerce APIs – For transaction processing.

▼ Java Messaging Service – For enterprise messaging services


such as reliable queuing, publish and subscribe
communication, and various aspects of push/pull
technologies.

▼ Java server platform – For Java back-end servers using the


Server Development Kit or for back-end servlets using the
Servlet Development Kit.

▼ Java Management API (JMAPI) – For interacting with JMAPI-


enabled applications that require system administration
activities.

Distributed Computing With Beans 9-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

Motivating Scenarios for Distributed Bean Programming

Future Enterprise JavaBeans


At the time this course was being written a new “Enterprise
JavaBeans” initiative was underway (announced at JavaOneSM in April
1997), which is an attempt to do for enterprise developers what
JavaBeans has done for application developers. A set of enterprise
service beans will provide modular components that insulate the
developer from the low-level protocol and networking portions of an
enterprise solution. These components provide some default
functionality that will empower developers to focus on the real
problem and employ the beans where there is a need to query a
database, do a named resource lookup, communicate through CORBA,
and the like.

Applications for Distributed Beans


This section provides a few examples for using JavaBeans components
in distributed applications.

9-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Motivating Scenarios for Distributed Bean Programming

Applications for Distributed Beans

Workflow Applications

JavaBeans components can be used in workflow applications in which


users retrieve blank invoices of some sort, fill them with content and
pass them along. The workflow continues through approval and filing,
usually with interaction from a second or third party.

This type of application transfers data from container to container.


Opportunities for beans exist in the clients that fill out, approve, and
file the forms. beans that represent forms themselves can have
customizers that change their format so they can be serialized as new
form types. Whereas the distributed workflow model described
previously follows a linear sequence of events, there is also a huge
potential for collaborative work done by multiple parties upon a single
object (for example, a whiteboard), or within a communal forum (for
example, a conference or chat room).

Application Servers

Application servers that enable data to be produced, consumed, and


observed also serve a variety of distributed computing solutions. For
example, a set of sensitive machinery producing power or oil, or even
computer hardware could have “smart” sensors that broadcast the
current level of activity through the producer interface to the
distributed system, and that activity can either be registered centrally,
in which case some sort of adapter would consume the events and
notify observers, or it could notify other interested peer observers
directly.

A number of listeners could chart the data to monitor progress or


could page interested parties in the event of an emergency or more
positive events that require attention. beans could be used in almost
any aspect of this model. They could represent abstractions of the
devices themselves or they could represent the notifiers and especially
the monitors. The beans could be tuned and customized with
particular network node locations for sources and targets with
thresholds that indicate more interesting information, and so forth.

Distributed Computing With Beans 9-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

Motivating Scenarios for Distributed Bean Programming

Applications for Distributed Beans

Agents

The concept of agents represents another interesting possibility for a


distributed model that involves beans. Agents consist of information
objects and an associated script that knows what to do with the
information and how to deal with the environment.1

Beans themselves are individual pieces of code that can easily model
behavior and attributes of real objects. They are in a sense small
applications themselves that can travel as objects from location to
location to retrieve or update data. The agent can act as a container for
data and it can also intelligently operate on that data in ways
appropriate to the data. Part of this intelligent operation involves
locating and invoking certain beans available within the environment
depending on the data. You can imagine a generation of object-
oriented database systems in which hundreds or thousands of agents,
possibly beans themselves, are cached for retrieval, and then asked to
carry out certain tasks upon themselves in a uniform way so that the
client retrieving the object need not concern itself with the semantics of
how to operate on the object's data.

1. Orfali, Harkey, and Edwards. The Essential Distributed Objects Survival Guide. (John
Wiley & Sons, Inc. 1996).

9-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Motivating Scenarios for Distributed Bean Programming

Applications for Distributed Beans

Agents (Continued)

In summary, agents are particularly good at providing security so that


the location where code is executed can be controlled, and at
providing interactive functionality so that the interface from the user's
perspective is consistent, yet the code within the agent is customized
to the data itself.

Distributed Computing With Beans 9-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
JavaSoft Distributed Computing Technologies

JavaSoft offers three technologies for use in distributed computing


environments. Each technology takes full advantage of the Java
programming language as an object-oriented language, and each
provides several benefits over technologies implemented with C and
other functional languages.

● JDBC API

● RMI API

● JavaIDL, representing CORBA

Figure 9-1 illustrates how JavaBeans components might be used in


distributed computing environments.

Database Database
J protocol
server
JavaBeans D
component B
C

JavaBeans IIOP
CORBA
component
server

JavaBeans RMI
component
Java
Server

Figure 9-1 Bean Components in Distributed Environments

The bean components act as intelligent front ends that communicate


with their network servers using the appropriate technology.

9-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Definition of JDBC

The JDBC API is a set of interfaces designed to insulate a database


application developer from a specific database vendor. The JDBC
enables the developer to concentrate on writing the application—
making sure that queries to the database are correct and that the data
is manipulated as designed.

JDBC API and Drivers


With JDBC, a developer can write an application using the interface
names and methods described in the API as though they are actual
class implementations, regardless of how they were implemented in
the driver. The driver vendor provides a class implementation of every
interface in the API so that when an interface method is used, it is
actually referring to an object instance of a class that implemented the
interface.

Application
makes calls to JDBC

JDBC driver
implements API for
specific database

Database

Figure 9-2 JDBC Overview

Distributed Computing With Beans 9-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Overview of JDBC Architecture

The interfaces provided by JDBC enable an application programmer to


open connections to particular databases, execute SQL statements, and
process the results. For example:

DriverManager

Driver Driver

Connection Connection

Connection Statement

ResultSet

Statement Statement Statement

ResultSet ResultSet

Figure 9-3 JDBC Connections, Statements, Queries, and Results

● A URL string can be passed to the getConnection() method of


the DriverManager, which in turn locates a Driver.

● With a Driver, you can obtain a Connection.

● With the Connection, you can create a Statement.

● You can execute a Statement with an executeQuery() method


and get a ResultSet returned.

9-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Notes

Distributed Computing With Beans 9-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
BeanBox JDBC Bean

The BeanBox provides a JDBC bean called JDBC SELECT that contacts
a database at a specified JDBC URL and runs a SQL SELECT statement
to display specified columns from a target table.

Note – You need access to an SQL database to use this bean.

A customizer class is provided with this bean to help in the somewhat


complex configuration. You can use the customizer to view available
database tables and select a target table. Then from the columns of the
target table that are displayed, you can choose which columns you
want displayed in the bean. Choosing targets updates the bean to
display the output of the corresponding SQL SELECT statement it
created for you. Several windows illustrating different stages of user
entries for the customizer bean are displayed in Figure 9-4 on page -15.

9-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
BeanBox JDBC Bean

Figure 9-4 Customizer for the JDBC SELECT Bean

Distributed Computing With Beans 9-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

BeanBox JDBC Bean

Advantages of Database-Related Beans


The JDBC SELECT bean provides added value to the user. A user does
not have to know much about query syntax. The customizer enables a
user to select the columns of a target table and automatically generate
the SELECT query.

Imagine other JDBC beans that provide other table manipulation


functionality, such as INSERT, DELETE, and UPDATE. If these also were
designed to construct the actual SQL query from the input received
from the user interface, the user would not have to understand SQL
query syntax in order to interface with the database.

9-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Definition of RMI

The RMI API is a set of classes and interfaces designed to enable the
developer to make calls to remote objects that exist in the runtime of a
different Java Virtual Machine (JVM) invocation. This “remote” or
“server” JVM can be executing on the same machine or on an entirely
different machine from the RMI “client.”

Unlike other RPC implementations, Java RMI is a pure Java-to-Java


mechanism that uses object serialization to send objects “over the
wire.” This enables a developer to pass complex data types across the
wire, an advantage RMI has over CORBA applications.

Implementation
Class
Client Server

Application Object
Implementation

Stub rmic (compiler) Skeleton

Method call

Method results

Figure 9-5 Overview of RMI

Note – The stub and skeleton classes are generated by the rmic
command using the implementation classes that were previously
compiled.

Distributed Computing With Beans 9-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
BeanBox RMI Bean

The QuoteMonitor bean provided with the BeanBox is an RMI bean. It


uses RMI to contact a remote quote server (such as Yahoo) and
displays real stock quotes for the stock specified in the bean.

Note – Imaginary stock quotes are generated if you start a local RMI
quote server.

QuoteMonitor
RMI Bean

Server
application

Figure 9-6 BeanBox QuoteMonitor Bean

✓ The idea for the RMI bean used in the exercise stems from this sample bean.

9-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Architecture Overview

A remote method invocation from a client to a remote server’s object


travels down through the layers of the RMI system to the client-side
transport, then up through the server-side transport to the server’s
object implementation.

As a developer, you are responsible only for creating the Java RMI
interface definitions and implementation classes, and for generating
the stub and skeleton classes with rmic. The Remote Reference layer
and Transport layer implementations are taken care of for you.

Application Java RMI Client Java RMI Server

Stubs Skeletons

RMI System Remote Remote


Reference layer Reference layer

Transport Transport

Figure 9-7 Graphical Overview of RMI Architecture

In the lab exercises, you will be asked to write the RMI client as a
JavaBeans component. This bean will replace the AdapterButton bean
used in the exercise that sent test data to the multiplexing adapter
bean. The remainder of the code for the RMI system (the RMI
interfaces, RMI implementation classes, and server) is provided for
you.

The RMI bean will communicate with the RMI server to request stock
data for a specific week.

Distributed Computing With Beans 9-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

RMI Architecture Overview

Transport Layer
The Transport layer is responsible for setting up the connection,
managing the connection, and keeping track of and dispatching
remote objects (the targets of remote calls) residing in the transport’s
address space.

Remote Reference Layer


The Remote Reference layer (RRL) is responsible for carrying out the
semantics of the method invocation. It manages communication
between the stubs and skeletons and the lower-level transport
interface using a specific remote reference protocol which is
independent of the client stubs and server skeletons. The RRL’s
responsibilities include managing references to remote objects and
reconnection strategies if an object should become unavailable.

9-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Architecture Overview

RMI Stubs and Skeletons


The Stub/Skeleton layer is the interface between the Application layer
and the rest of the RMI system. This layer does not deal with any of
the specifics of any transport, but transmits data to the RRL.

A client invoking a method on a remote server object actually makes


use of a stub or proxy for the remote object as a conduit to the remote
object. A skeleton for a remote object is a server-side entity that
dispatches calls to the actual remote object implementation.

rmic Command
The rmic command creates stub and skeleton code from the interface
and implementation class definitions. The RMI interface and
implementation classes must be compiled before the rmic command is
executed. The rmic command is then run on the implementation
classes.
✓ The rmiCode.jam makefile, provided in the SL291files/work directory, invokes the Rmic
rule (see jambase). Rmic runs the rmic command.

rmiregistry Application
The rmiregistry is an application that provides a simple naming
lookup service. The server application provides rmiregistry with
the object reference and a String name through the rebind method
call.

Note – The rmiregistry must be running before the server


application is started and attempts to bind.

Distributed Computing With Beans 9-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Exercise Description
The DataServer application creates a set of objects that have data
associated with them. Each of these objects has a unique ID. The IDs
are displayed in a list by the DataClient bean. When a user selects an
item in the client list, the client requests the data from the server
associated with this ID. The client then creates a DataEvent event
using the data it received from the server and fires this event to the
multiplexing adapter bean.

Server
Client

DataFactory
Constructs
DataEvent Get data information Creates
from data
retrieved
from server Data
instance

Figure 9-8 Conceptual Overview of RMI Exercise

9-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Source Files Provided


The following source files are provided in the exercise: Data.java,
DataFactory.java, DataImpl.java, DataFactoryImpl.java, and
DataServer.java. You will write the DataClient.java file that
defines the RMI bean. Figure 9-9 illustrates how the various source
files fit into the conceptual overview shown in Figure 9-8 on page 22.

DataClient.java DataServer.java

DataFactory.java DataFactoryImpl.java
(interface)
Data DataImpl.java
Data.java
(interface) instance

List of DataImpl IDs


% rmiregistry&
% java DataServer

Figure 9-9 Source File Overview of RMI Exercise

✓ It might be beneficial to review on the whiteboard the definition of the DataEvent object
because the RMI code described on the following pages was written based on this event
object. The DataEvent object was created in Module 8; recall that the DataEvent object

• Defines the following data members:

• private String [][] data;

• private String [] xAxis;

• private String [] yAxis;

• private String ID, xLabel, yLabel;

• Defines a constructor with one argument which is the source component.

• Defines get and set methods for each of the private data members.

Distributed Computing With Beans 9-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Interfaces
There are two interface classes used in the RMI exercise, Data and
DataFactory.

Note – The RMI API defines many exception types that your code
must be written to handle. Make note of the exceptions and exception
handling that are used in the RMI exercise code that is discussed in the
next several pages.

Data.java File

The Data.java file defines an interface that is implemented by


DataImpl.java.
1 package sl291.rmilab;
2
3 import java.rmi.*;
4 import java.awt.Dimension;
5
6 public interface Data extends Remote{
7
8 public String getID() throws RemoteException;
9
10 public String getXLabel() throws RemoteException;
11
12 public String getYLabel() throws RemoteException;
13
14 public String [] getXAxis() throws RemoteException;
15
16 public String [] getYAxis() throws RemoteException;
17
18 public Dimension getSize() throws RemoteException;
19
20 public String [] [] getDataValues() throws RemoteException;
21 }

9-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Interfaces (Continued)

DataFactory.java File

The DataFactory.java file defines an interface that is implemented


by DataFactoryImpl.java.
1 package sl291.rmilab;
2
3 import java.rmi.*;
4
5 public interface DataFactory extends Remote{
6
7 public Data getData(String id) throws RemoteException;
8 public String [] getDataList() throws RemoteException;
9 public void addData(DataImpl dImpl) throws RemoteException;
10 }

Distributed Computing With Beans 9-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Implementation Classes

DataImpl.java File

The DataImpl.java file defines methods to access the data provided


for a DataImpl object by the DataServer application. This data is then
used by the DataClient bean to construct a DataEvent event.

Note – The UnicastRemoteObject class is the parent class of each


RMI implementation class.

✓ Currently, multicast remote objects and replication are not supported.

1 package sl291.rmilab;
2
3 import java.rmi.*;
4 import java.rmi.server.*;
5 import java.awt.Dimension;
6
7 public class DataImpl extends UnicastRemoteObject implements Data{
8
9 private String id, xLabel, yLabel;
10 private String [] xAxis, yAxis;
11 private String [][] dataValues;
12 private Dimension size;
13
14 public DataImpl(String id, String xLabel, String yLabel)
15 throws RemoteException {
16
17 this.id = id;
18 this.xLabel = xLabel;
19 this.yLabel = yLabel;
20 this.size = new Dimension (8,5);
21 xAxis = new String [size.height];
22 yAxis = new String [size.width];
23 dataValues = new String [yAxis.length] [xAxis.length];
24 }
25
26 public String getID() throws RemoteException {
27 return id;
28 }

9-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Implementation Classes
29 public String getXLabel() throws RemoteException {
30 return xLabel;
31 }
32
33 public String getYLabel() throws RemoteException {
34 return yLabel;
35 }
36
37 public String [] getXAxis() throws RemoteException {
38 return xAxis;
39 }
40
41 public String [] getYAxis() throws RemoteException {
42 return yAxis;
43 }
44
45 public Dimension getSize() throws RemoteException {
46 return size;
47 }
48
49 public String [] [] getDataValues() throws RemoteException {
50 return dataValues;
51 }
52
53 public void setXAxis(String [] sa1) {
54 xAxis = sa1;
55 }
56
57 public void setYAxis(String [] sa2) {
58 yAxis = sa2;
59 }
60
61 public void setSize(int width, int height) {
62 size = new Dimension(width, height);
63 }
64
65 public void setDataValues(String [] [] sa3) {
66 dataValues = sa3;
67 }
68 }

Distributed Computing With Beans 9-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Implementation Classes

DataFactoryImpl.java File

The DataFactoryImpl object maintains a vector of DataImpl objects,


defines a method for retrieving the data for a specified DataImpl
object, and defines a method for retrieving a list of IDs for the
DataImpl objects it maintains. This list is used to populate the list of
the DataClient bean.
1 package sl291.rmilab;
2
3 import java.rmi.*;
4 import java.rmi.server.*;
5 import java.util.Vector;
6
7 public class DataFactoryImpl extends UnicastRemoteObject implements
8 DataFactory{
9
10 private Vector storage;
11
12 public DataFactoryImpl() throws RemoteException {
13 storage = new Vector(1,1);
14 }
15
16 public Data getData(String id) throws RemoteException {
17 for (int i = 0; i < storage.size(); i++) {
18
19 if (((DataImpl)storage.elementAt(i)).getID().equals(id)){
20 return (Data)storage.elementAt(i);
21 }
22 }
23 return null;
24 }

9-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Implementation Classes

DataFactoryImpl.java File (Continued)

25 public String [] getDataList() throws RemoteException {


26 String [] names = new String [storage.size()];
27
28 for (int i = 0; i < storage.size(); i++) {
29 names[i] = ((DataImpl)(storage.elementAt(i))).getID();
30 }
31 return names;
32 }
33
34 public void addData(DataImpl dImpl) throws RemoteException {
35 storage.addElement(dImpl);
36 }
37
38 }

Distributed Computing With Beans 9-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

RMI Exercise Code

Server Code Overview


The following is done in the DataServer application:

● Creating and installing a security manager

Note – RMI applications must have a security manager installed in


order to load classes using RMIClassLoader.

● Instantiates a DataFactoryImpl object, dfi.

9-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
RMI Exercise Code

Server Code Overview (Continued)


● Publishes the dfi object by binding the object to a name that is
stored in the lookup application, the rmiregistry.

The “binding” occurs using the statement


Naming.rebind("dataServer", dfi);

This method associates or “binds” the name dataServer to the


dfi object, removing any object previously bound with this name
from the registry.

● Creates DataImpl objects and populates them with data.

● Adds the DataImpl objects to the vector maintained by the dfi


object.

Distributed Computing With Beans 9-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9

CORBA/JavaIDL (Optional)

The JavaIDL API is actually a Java approach to the CORBA


technology. CORBA is similar to RMI, but abstracts the definition of
the client and server interfaces further. The client and server code is
generated from a specification file (IDL) that defines the
implementation of each object service. Using JavaIDL or CORBA
technology, you can wrap existing legacy code (C, C++, COBOL) to
allow problems to be modeled in a single language (IDL) and then
compiled to other languages.

Unlike RMI (a Java-to-Java solution), CORBA implementations


support multiple languages across multiple platforms. For example, if
you had a legacy application that provided stock quotes for you, you
could wrap the application in a CORBA implementation (such as
JavaIDL), and write a bean to interface with the CORBA
implementation. The bean might visually look the same as the RMI
bean, but the interface mechanism to the server would be different.
✓ There is no detail provided here because discussing CORBA can become very involved
and there are currently no demo beans provided with the BDK to illustrate such a bean.

9-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Exercise: Creating an RMI Client Bean

Exercise objective – The objective of this exercise is create an RMI


bean that retrieves data from a server and supplies that data in a
DataEvent to the multiplexing adapter. Essentially, the RMI bean
replaces the AdapterButton bean used in the adapter exercise.

Preparation
To be prepared for this exercise, you should have completed the code
from the exercise on adapters: the DataEventMultiplexer,
DataEvent, and DataEventListener classes should be written. You
will need these classes to test the DataClient bean you will write in
this exercise. If you did not finish the adapter exercise code, use the
solutions provided with the adapter module to complete your code
before beginning this exercise.

Note – Be sure the value of your CLASSPATH variable includes


$JAVA_HOME/lib/classes.zip, SL291files/work, and . (the
current directory) before starting the rmiregistry.

✓ If the rmiregistry is started and the JDK class files are not included in CLASSPATH, there is
a binding problem with the server and error messages are generated when you start the
RMI server. In addition, you cannot instantiate the DataClient bean in the BeanBox.

✓ The DataClient is created as a unicast source for the same reasons as the AdapterButton
bean supplied in the multiplexing adapter lab.

Distributed Computing With Beans 9-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Exercise: Creating an RMI Client Bean

Tasks

Creating the RMI Bean and JAR File

Note – Remember that when writing your DataClient bean, you must
catch exceptions that might occur when you make a request from the
server or do a name lookup in the RMI registry. Also, import
java.rmi.*.

1. Change to the SL291files/work directory.

2. Create a file called DataClient.java that defines the DataClient


bean. The DataClient bean satisfies the following specifications:

▼ Is a List component

▼ Implements the ActionListener interface

▼ Defines a constructor that:


● Creates a list that does not allow multiple selections.
● Registers itself as a listener for ActionEvent events
● Gets the DataFactory instance from the registry using the
following method:

(DataFactory)Naming.lookup("//localhost/dataServer"
)

● Retrieves the list of DataImpl object IDs from the


DataFactory object and populates its list with them.

9-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Exercise: Creating an RMI Client Bean

Tasks

Creating the RMI bean and JAR File (Continued)

▼ Is a unicast source for DataEvent events

▼ Defines the actionPerformed method that:


● Uses the DataFactory object to retrieve the data associated
with the user-selected item in the list
● Creates a DataEvent event from the data retrieved
● Fires the DataEvent to the registered DataEventListener

3. Change to the SL291files/work directory.

4. Generate the rmilab.jar file.

% jam -sjf=rmiCode.jam

Distributed Computing With Beans 9-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Exercise: Creating an RMI Client Bean

Tasks

Testing the DataClient Bean

1. Start the DataServer application.

% java sl291.rmilab.DataServer &

2. Restart the BeanBox and test the DataClient bean.

DataClient
DataTableBean
(Table)
ent
Fires DataEvent
Ev
b le
Ta
ta DataTableBean
Da
nt (XAxis)
DataT ableEve
DataEventMultiplexer
Data
Tabl
eEve DataTableBean
nt
(YAxis)

Figure 9-10 Overview of Bean Hookup

Create instances of the beans from the adapter exercise, replacing


the AdapterButton bean with the DataClient bean. Hook the
beans up as shown in Figure 9-10.

9-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Exercise: Creating an RMI Client Bean

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” If you do not have time to spend on discussion, then just
highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

Distributed Computing With Beans 9-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Describe, in one paragraph, the JDBC architecture.

❑ How might a bean component work with JDBC?

❑ Draw a diagram that illustrates the main concepts of the Java RMI
architecture.

❑ How would you implement a Java RMI bean for a given RMI
application?

❑ Create bean components to be used on the client side of a Java


RMI application.

9-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
9
Think Beyond

You have been running and testing bean components using the
BeanBox. The BeanBox is not considered an application builder tool.
Without such a tool, how do you use your beans and build an
application that runs outside of the BeanBox?

Distributed Computing With Beans 9-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Beans Outside of the
BeanBox 10

Course Map
In this module, you will write the code necessary to utilize beans in
applets or applications.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

10-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Relevance

✓ Present the following question to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – Think about what went on when you were connecting


components in the BeanBox and testing them. What extra work was
the BeanBox performing to help your beans interact in the ways you
wanted?

✓ The BeanBox builds adapters that connect your beans to one another. This Java source is
built automatically and compiled when events are connected to targets.

10-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Objectives

Upon completion of this module, you will be able to:

● Assess the use of the BeanBox as a minimal environment for


testing and using beans.

● Describe the requirements for creating an applet or application


using existing bean components.

● Provide examples of the various scenarios for building beans.

● Explain how digital signatures can be used to make an “official”


bean.

● Create an applet that uses existing bean components and run it in


the Applet Viewer.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JAR Guide. [On-line]. Available:


http://www.javasoft.com:80/products/jdk/1.1/
docs/guide/jar/jarGuide.html.

● Manifest Format. [On-line]. Available:


http://www.javasoft.com:80/products/jdk/1.1/
docs/guide/jar/manifest.html

● The Javakey Security Tool – javakey. [On-line]. Available:


http://java.sun.com/products/jdk/1.1/docs/
tooldocs/solaris/javakey.html

● Why should I care about X.509 certificates. [On-line]. Available:


http://java.sun.com/products/jdk/1.1/docs/
guide/security/cert2.html

● Java Security. [On-line]. Available:


http://java.sun.com/security/codesign/index.html

● J/Crypto from Baltimore Technologies. [On-line]. Available:


http://www.baltimore.ie/jcrypto.htm

Beans Outside of the BeanBox 10-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Options for Building Beans

This overview examines the different scenarios within which a


developer might build a bean. These scenarios include the following:

● Building a bean from scratch

● Inheriting from a bean to form a new bean

● Subclassing a bean and adding a BeanInfo file

● Composing a bean from other beans

● Instantiating a bean from a serialized prototype

Building a Bean From Scratch


The developer can programmatically (by hand), or with the aid of
builder tool, write a bean from scratch without incorporating other
beans. Most of the beans in the BDK were built this way.

10-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building Beans

Inheriting From a Bean


A class that is a bean can be extended (inherited from) just as normal
classes can. So the feature set of one bean can form the foundation of a
new, similar bean that adds to or changes features. Even an applet that
is a bean can be extended to create another bean applet.

Sample Code

In the BDK demo directory, sunw.demo.sort.SortAlgorithm is an


applet and a bean whose sort algorithm can be specified.

The classes QSortAlgorithm, BubbleSortAlgorithm, and


BidirBubbleSortAlgorithm extend the SortAlgorithm applet/bean
and set the sortAlgorithm property to specific algorithms.

In addition, a non-bean applet can be turned into a bean that can


either be configured using getParameter() in its init() method or
configured completely through properties.

Beans Outside of the BeanBox 10-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Options for Building Beans

Subclassing a Bean and Adding BeanInfo


As a bean developer, you do not always have the luxury of modifying
the source code of a bean to add or limit properties, methods, or
events. Sometimes it makes more sense to keep the bean generic and
create a set of specialized versions. In other cases, you may have
obtained a bean from a third party who did not supply source code.
The example below shows how extensible beans are. Since
introspection automatically locates properties, events, and methods
within super-classes, adding a new layer of features works very well.

Subclassing a Bean

Create a new class by extending


sunw.demo.buttons.ExplicitButton from OurButton:
public class ExplicitButton extends OurButton { }

Then define a BeanInfo file for the bean.

10-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building Beans

Subclassing a Bean and Adding BeanInfo

Adding a BeanInfo File

In the code fragments below that compose the BeanInfo file for the
ExplicitButton bean, the following items are addressed:

● Restricting visible properties on the PropertySheet window

● Adding icons for the bean

● Specifying a customizer for the bean

● Limiting visible events displayed on the Edit ➤ Events submenu

Restricting Visible Properties

The visible properties are restricted to the background, foreground,


font, and label properties. The BeanInfo file also indicates that these
four properties are to be bound properties.
1 public PropertyDescriptor[] getPropertyDescriptors() {
2 try {
3 PropertyDescriptor background =
4 new PropertyDescriptor("background", beanClass);
5 PropertyDescriptor foreground =
6 new PropertyDescriptor("foreground", beanClass);
7 PropertyDescriptor font = new PropertyDescriptor("font",
8 beanClass);
9 PropertyDescriptor label =
10 new PropertyDescriptor("label", beanClass);
11 background.setBound(true);
12 foreground.setBound(true);
13 font.setBound(true);
14 label.setBound(true);
15
16 PropertyDescriptor rv[] = {background, foreground, font, label};
17 return rv;
18 } catch (IntrospectionException e) {
19 throw new Error(e.toString());
20 }
21 }

Beans Outside of the BeanBox 10-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Options for Building Beans

Subclassing a Bean and Adding BeanInfo

Adding a BeanInfo File (Continued)

Adding Icons

Indicate what icons are to be associated with the bean.


1 public java.awt.Image getIcon(int iconKind) {
2 if (iconKind == BeanInfo.ICON_MONO_16x16 ||
3 iconKind == BeanInfo.ICON_COLOR_16x16 ) {
4 java.awt.Image img = loadImage("ExplicitButtonIcon16.gif");
5 return img;
6 }
7 if (iconKind == BeanInfo.ICON_MONO_32x32 ||
8 iconKind == BeanInfo.ICON_COLOR_32x32 ) {
9 java.awt.Image img = loadImage("ExplicitButtonIcon32.gif");
10 return img;
11 }
12 return null;
13 }

Specifying a Customizer for the Bean

Specify the customizer associated with the bean.


1 public BeanDescriptor getBeanDescriptor() {
2 return new BeanDescriptor(
3 ExplicitButton.class, OurButtonCustomizer.class);
4 }

10-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building Beans

Subclassing a Bean and Adding BeanInfo

Adding a BeanInfo File (Continued)

Limiting Visible Events

The visible events for the bean are limited to the “button was pushed”
event (indicated by the actionPerformed method) and the “property
was changed” event (indicated by the propertyChanged method).
1 public EventSetDescriptor[] getEventSetDescriptors() {
2 try {
3
4 EventSetDescriptor push = new EventSetDescriptor(beanClass,
5 "actionPerformed", java.awt.event.ActionListener.class,
6 "actionPerformed");
7
8 EventSetDescriptor changed = new EventSetDescriptor(beanClass,
9 "propertyChange", java.beans.PropertyChangeListener.class,
10 "propertyChange";
11
12 push.setDisplayName("button push");
13
14 changed.setDisplayName("bound property change");
15
16 return EventSetDescriptor[] rv = { push, changed};
17
18 } catch (IntrospectionException e) {
19 throw new Error(e.toString());
20 }
21 }

Beans Outside of the BeanBox 10-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Options for Building Beans

Composing a Bean From Other Beans


A bean can also be created from several other beans.

● Beans can be used just like classes or, preferably, instantiated to


reap the benefits that the bean framework provides.

Note – When choosing to use beans.instantiate() instead of new, it


is also important to use the isInstanceOf() or getInstanceOf()
methods provided by the java.beans.Bean class.

● This involves the creation of a “higher level” bean constructed


from smaller building blocks.

Note – The composite bean is responsible for making sure all beans are
read and written properly, and for restoring connections between
beans in the event that a composite bean is loaded from a persisted
state.

10-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building beans

From a Serialized Prototype


You can save the state of an existing bean whose properties have been
customized to meet a new or specialized purpose. This creates a
serialized bean prototype (a .ser file) that can be re-instantiated like a
normal bean within an application.

Customizing and Saving a Bean

The code below is used to customize a property of the Molecule bean


(sets the MoleculeName property to benzene) and serialize the
customized bean in the sunw/demo/molecule/moleculeSerFile.ser
file.
1 import java.beans.*;
2 import sunw.demo.molecule.*;
3 import java.io.*;
4
5 // Create the serialized file of molecule changed to Benzene
6 public class MyMolSer {
7 private static Molecule moleculeB;
8
9 public MyMolSer() {
10 ClassLoader cl = null;
11 try {
12 cl =
13 Class.forName("sunw.demo.molecule.Molecule").getClassLoader();
14 moleculeB = (Molecule)
15 Beans.instantiate(cl,"sunw.demo.molecule.Molecule");
16 moleculeB.setMoleculeName("benzene");
17 FileOutputStream fos = new
18 FileOutputStream("sunw/demo/molecule/moleculeSerFile.ser");
19 ObjectOutputStream outputStream = new ObjectOutputStream(fos);
20 outputStream.writeObject(moleculeB);
21 } catch ( Exception e) {
22 throw new Error(e.toString());
23 }
24 }

Beans Outside of the BeanBox 10-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building Beans

From a Serialized Prototype

Customizing and Saving a Bean (Continued)

25 public static void main (String args[]) {


26 MyMolSer m = new MyMolSer();
27 }
28 }

To create a serialized benzene Molecule bean, type the following


command from the command line in the demo directory of the BDK:
% java MyMolSer

10-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Options for Building Beans

From a Serialized Prototype

Restoring the Bean

The following application instantiates a bean from the .ser file that
was created previously:
1 import java.awt.Frame;
2 import java.awt.Component;
3 import java.beans.Beans;
4 import java.io.*;
5
6 // Read the serialized file and display the bean
7 public class BeanUnSer extends Frame {
8 private static Component myBean;
9 public BeanUnSer(String beanSerFile) {
10 super("Unserialized from: "+beanSerFile);
11 try {
12 myBean = (Component) Beans.instantiate(null,beanSerFile);
13 } catch ( Exception e) {
14 System.out.println("Error unserializing bean " +
15 beanSerFile+ ": "+e);
16 }
17 this.add(myBean);
18 this.setSize(300,300);
19 this.show();
20 }
21
22 public static void main (String args[]) {
23 BeanUnSer m = new BeanUnSer(args[0]);
24 }
25 }

To demonstrate instantiating a serialized bean, type the following


command from the command line:
% java BeanUnSer sunw.demo.molecule.moleculeSerFile

Beans Outside of the BeanBox 10-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Creating Applets and Applications With Beans

Applets, applications, or other programs that use beans can be created


with any of the ways indicated on the above overhead.

10-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Creating Applets and Applications With Beans

Using a Builder Tool (IDE/RAD Tool)


✓ Refer students to Section 3.1 of the beans specification 1.0a for a detailed scenario. The
specific steps will change from builder tool to builder tool so an overview which the
students can follow as they learn their specific tools is given here.

The following steps are involved with using a builder tool to create
applets or applications that use beans:

1. Obtain a bean-aware builder tool, and a set of bean components.

2. Lay out the applet, dragging JDK classes and bean components
from the toolbar onto the GUI surface.

3. Customize the beans by editing their property sheets and using


their customizers.

4. Connect the beans, choosing source events and their target


methods on other beans, and filling out where necessary with
specific code.

5. Package the applet by having the builder tool serialize the


modified beans, build the source code of the connecting pieces,
and save everything into a JAR file.

6. Test the new applet in run mode.

Beans Outside of the BeanBox 10-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Creating Applets and Applications With Beans

Coding Programmatically
✓ Refer students to Section 3.2 of the beans specification 1.0a for a detailed scenario.

The same steps that are used with a builder tool apply to coding by
hand, except an entire applet or application must be written including
all the adapter classes that make addXXXListener calls between
event listeners and event sources, all the Beans.instantiate method
calls, and so forth. See the example on page 43 for details.

Scripting
A scripting language works at an extremely high level. Script
commands provide high-level, generic but practical functionality that
would normally take hundreds of lines of code to develop.

With languages such as JavaScript™ or Tcl/Tk, programs can be


created that can save hundreds of lines of code with a few statements.

10-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Issues for Applets That Are Beans

Note – You saw earlier that an applet can be built from beans, but an
applet can also be a bean.

The following issues can arise with applets that are beans or that are
composed of beans:

● Handling parameters supplied by PARAM tags so they coexist as an


alternative method along with properties.

● Catering to the life cycle of an applet even though it is a bean.

What happens during design time? During runtime? How do


property changes and events that modify state affect the running
thread?

● Ensuring that serialization works properly to revive the applet and


launch it back into its life cycle without hitches.

Beans Outside of the BeanBox 10-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Delivering Your Beans

JAR files were described briefly in Module 2. This module will take an
advanced look at how they fit into the larger scheme of how beans are
used.

A Set of .class Files


Until recently, supplying a set of .class files was the only option for
delivering code. Either a set of classes was downloaded as part of an
application and installed locally, or an applet’s CODEBASE tag enabled a
browser to locate classes it needed and download them individually
from a remote location.

Classes that represent beans still could be made available this way, but
the practice is discouraged, not specifically supported, and sacrifices
many of the advantages JAR files provide.

10-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Delivering Your Beans

How Are JAR Files Used?


The JavaBeans specification recommends packaging all JavaBeans
components in JAR files for distribution. These JAR files then can be
used in the following contexts:

● JARs can be loaded into your builder tool (as you saw with the
BeanBox).

● JARs can be located in your CLASSPATH.

● JARs can be used in HTML files with the OBJECT or APPLET tags as
an alternate source besides CODEBASE or local CLASSPATH (more
on this later).

JAR File Review


Recall that a JAR file is just a ZIP file plus an optional MANIFEST
(description) file.

Here are some sample entries for the MANIFEST portion of a JAR file.
Notice that not all classes are beans.
Name: sl291.dataTable.DataTableBean.class
Java-Bean: True

Name: sl291.dataTable.DataTableBeanBeanInfo.class
Java-Bean: False

Name: sl291.dataEvent.DataEventMultiplexor.class
Java-Bean: True

Beans Outside of the BeanBox 10-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Delivering Your Beans

Using JAR Files in HTML


JAR files that include an applet bean can be used in HTML code by
using either the APPLET tag or the OBJECT tag.

APPLET Tag

As Java programmers you should already be familiar with the APPLET


tag, so only the new information that relates to beans will be discussed
here.

10-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Delivering Your Beans

Using JAR Files in HTML

APPLET Tag (Continued)

When creating an HTML file for running a bean applet in a browser,


you should:

● Use the APPLET tag with:

▼ ARCHIVE=fooJar.jar and either CODE=foo.class or


OBJECT=fooApplet.ser.

Note – The above OBJECT is the OBJECT attribute of the APPLET tag,
not the OBJECT tag discussed on page 22.

▼ CODEBASE to specify subdirectories.

● Be aware that init() is not invoked, but start() is.

● Know the restriction about which properties are restored when the
applet is loaded from a serialized state.

● Understand that you must call stop() in the applet before


serializing it.

● Be aware that the NAME tag supplies a name so multiple applets


loaded on the same page can communicate with each other.

Note – A recent JDK change makes all applets on a page use the same
class loader.

✓ Is this true even if the applets are loaded from entirely different servers?

Beans Outside of the BeanBox 10-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Delivering Your Beans

Using JAR Files in HTML

OBJECT Tag

The OBJECT tag is a proposed extension beyond HTML 3.2 that was
introduced as a generic way to identify a range of object types. The
OBJECT tag contains several attributes that are not part of the APPLET
tag.

● DATA – The URL for the object’s data; for example, a bean class
object.

● TYPE – Specifies the Internet Media (Mime) type for the data
referenced by the DATA parameter.

● CLASSID – The URL that identifies an implementation for the


object. Similar to DATA but meant to avoid a network access when
objects are local.

● CODETYPE – Similar to TYPE but meant to avoid a network access


when objects are local.

10-22 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Delivering Your Beans

Using JAR Files in HTML


✓ Refer students to the specification for the complete set of attributes.

One of the great advantages of the OBJECT tag is its support of


customized versions of beans in the form of serialized data.

HTML Code Example

<OBJECT
WIDTH=300 HEIGHT=100
CODETYPE="juggler.jar"
NAME="FastJuggler"
TYPE="application/x-java-serialized-object"
DATA="sunw/demo/juggler/FastJuggler.ser"
>
</OBJECT>
✓ Note that JDK 1.1 datatransfer.DataFlavor used the wrong MIME type for serialized
objects. It used application/x-javaserializedobject. Other valid types as of JDK 1.1
include application/java-vm, application/x-java-vm and application/x-java-archive.

Beans Outside of the BeanBox 10-23


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

Another advantage JAR files can add in terms of bean distribution is


that JAR files can contain digital signatures.

Definition
A digital signature is the result of an algorithmic computation on data
using a private key.

Why Use Digital Signatures?


A digital signature is like a handwritten signature, but for electronic
data. One reason to use digital signatures is to provide a means for a
user to verify the author or publisher of a bean and its integrity.

10-24 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
JAR Files With a Digital Signature

Comparing Handwritten and Digital Signatures


A document that is signed with a handwritten signature in the
presence of a neutral notarizing public entity is considered to be
official. In this way, someone receiving the document can trust that
whoever signed the document authenticates and agrees with, or is at
least aware of, its content.

Similarly, digitally signed data (such as an HTML document, bean, or


applet) is made official when the signing entity uses a private key to
sign it, and that signature can be verified using a certificate from a
trusted Certification Authority. In this way, the receiver of the signed
data can trust that the data has been produced by or provided by a
specific entity such as a banking institution, a business partner, or even
one’s mother.

Unlike handwritten signatures, a digital signature is designed so that it


is based on complex keys and encryption algorithms in such a way
that the signature can be verified, but it cannot be forged. Forging a
digital signature would require obtaining a private key from a public
key, and compromising Certification Authorities who have taken legal
responsibility for providing authentic certificates. Determining a
private key from a public key is sufficiently difficult that it is not
generally considered a risk.

Digital Signatures and Beans in JAR Files


JAR files that have been signed with a digital signature can provide
beans that are considered “official.” Such beans could include those
published by a known and trusted entity such as your favorite
banking organization or a business partner.

So for example, a banking application that relies on a set of beans in a


JAR file that accepts credit card or account information must be as
trustworthy to a customer using that application as a bank teller in a
banking institution.

Beans Outside of the BeanBox 10-25


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

Digital Signatures and Certificates


You do not need to know much about certificates. An identity
certificate is a digitally signed statement from one entity, stating that a
public key of another entity has some particular value. A Certification
Authority (CA) is trusted to issue and maintain databases of
certificates for other entities. Registering with a CA means an entity
that receives an alleged public key from an organization can check
with a CA to ensure it was not created in an attempt to commit fraud.
The X.509 definition says that a certificate is a formatted bundle of
data containing the following:

● Digital signature – Computed from data and private key.

● Version number – Identifies the version of the X.509 standard to


which the certificate conforms.

● Unique subject name – Identifies the subject of the data signed and
the entity who signed it.

10-26 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
JAR Files With a Digital Signature

Digital Signatures and Certificates (Continued)


● Public key – Specifies the public key for the entity being named.

● Issuer name – Specifies the issuer, usually the Certification


Authority.

● Serial number – Indicates the serial number for distinguishing an


entity’s certificate from others it creates.

● Validity period – Specifies the length of time during which the


certificate is valid, ranging from seconds to years.

Beans Outside of the BeanBox 10-27


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

Fitting the Pieces Together


The developer of the JAR file content uses a tool like javakey to sign
the contents. A JAR file can also be a combination of objects signed by
multiple entities. Figure 10-1 shows an overview of how the various
items involved with digital signatures fit together.

Private key

Java key Signed JAR Verify


JAR file tool file signature

Certificate

Figure 10-1 Overview of Digital Signatures

10-28 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
JAR Files With a Digital Signature

Fitting the Pieces Together (Continued)


For example, an enterprise that supplies applets to do banking over
the Web might create applets that are built from beans. Some of these
Beans might be provided by a conglomerate of financial institutions.
Digital signatures for both the banking beans and the enterprise’s final
applet could be combined into a single JAR file that is accessed from
an HTML page using an APPLET or OBJECT tag.

Products Using Signed Code

The JavaServer Toolkit is an example of a product that uses signed


code. It includes the following security features:

● Secure Sockets (SSLv3) support

● https:// URL handler (HTTP over SSL)

● Signed code, leveraging the JDK 1.1 digital signature support and
signed JAR files

Beans Outside of the BeanBox 10-29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

Security and Cryptography


Digital signatures add another layer of security to that already
provided by the Java programming language. However, recall from
‘‘Security’’ on page 1-24 in Module 1, ‘‘Overview of JavaBeans,”
supplying a digital signature with a component does not, in itself,
restrict access to the local resources.
✓ Providing a digital signature on a bean provides a mechanism for checking the bean
against a list of trusted parties.

In addition, encryption can provide yet another security layer. The


Java programming language provides a Java Cryptography
Architecture (JCA) API specification and reference a
http://java.sun.com/products/jdk/1.1/docs/
guide/security/CryptoSpec.html. This API can provide ways to
reliably encrypt and decrypt JAR contents.

10-30 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
JAR Files With a Digital Signature

Security and Cryptography (Continued)


J/Crypto, from Baltimore Technologies, is fully compliant with the
JCA as a Java Cryptography Extension (JCE) and can be used for any
Java application including:

● Internet communication

● File storage and retrieval

● Digital signatures

● Message hashing

Beans Outside of the BeanBox 10-31


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

What Tools Are Involved?


The following tools are involved with creating a JAR file with a digital
signature:

● Java Security API methods and classes, such as


java.security.Signature and
java.security.SignatureEngine – Interfaces, classes, and
algorithms for generating or implementing signatures and keys.

● JAR tool – Builds JAR files.

● javakey – Generates digital signatures, verifies signatures, can


maintain a database of public and private keys and certificates. See
http://java.sun.com/products/jdk/1.1/docs/tooldocs/solaris/javakey.html

Note – At the time of this writing, verification of digital signatures in


JAR files was not implemented in javakey.

● Other applications such as HotJava, Netscape, Java Web Server –


Have built-in facilities for working with signatures and
certificates.

10-32 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

JAR Files With a Digital Signature

For More Information


If you are interested in digital signatures and cryptography, refer to
the appropriate URL below:

● The Javakey Security Tool – javakey at


http://java.sun.com/products/jdk/1.1/docs/tooldocs/
solaris/javakey.html

● Why should I care about X.509 certificates? at


http://java.sun.com/products/jdk/1.1/docs/guide/
security/cert2.html

● Java Security at
http://java.sun.com/security/codesign/index.html

● J/Crypto from Baltimore Technologies at


http://www.baltimore.ie/jcrypto.htm

Beans Outside of the BeanBox 10-33


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Loading and Instantiating a Bean

Instantiating a bean in any program involves the following steps:

1. Supplying the bean’s class files or serialized state along your


CLASSPATH or within a JAR file, identifying the full pathname or
package name to the class, and determining the class type.

2. Identifying the class loader that will load your bean.

3. Obtaining the class loader object.

4. Instantiating the bean using Beans.instantiate().

10-34 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Loading and Instantiating a Bean

Coding Possibilities
There are several cases for writing code to load and instantiate a bean.
These involve loading and instantiating a bean within various
contexts:

● From within a Java applet off a server using the applet’s class
loader

● From within an application using:

▼ The class loader for the bean class or, if this is null, the System
class loader

▼ A class loader method to load a bean from a URL (local or


remote)

▼ A class loader that “understands” how to find beans in JAR


files

● From a serialized stream

Beans Outside of the BeanBox 10-35


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Loading and Instantiating a Bean

Instantiating a Bean in an Applet


The code below illustrates how to load and instantiate a bean from
within a Java applet. The class loader that is used for instantiating the
bean is the class loader for the applet:
1 ClassLoader cl = this.getClass().getClassLoader();
2 myBean = (MyBean) Beans.instantiate(cl, "myorg.mypkg.MyBean")

Instantiating a Bean in an Application

Using Bean Class or System Class Loader

The following code shows how to load and instantiate a bean from
within an application. The class loader used is either the class loader
associated with the bean class, or, if this is null, the System class
loader.
1 import myorg.mypkg.MyBean;
2 ...
3 ClassLoader cl = Class.forName("myorg.mypkg.MyBean").getClassLoader();
4 myBean = (MyBean) Beans.instantiate(cl, "myorg.mypkg.MyBean");

10-36 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Loading and Instantiating a Bean

Instantiating a Bean in an Application

Using a JAR File

The code below illustrates how to use a JAR file to load and instantiate
a bean. The JarLoader class is defined as part of the BeanBox code.
1 import sun.beanbox;
2 ...
3 JarLoader jl = new JarLoader(jarFileName);
4 ClassLoader cl = jl.getLoader();
5 JarInfo ji = jl.loadJar();
6 Component myBean = (Component)
7 Beans.instantiate(cl,beanClassName);
✓ try and catch statements were left out intentionally for simplicity.

✓ The JarLoader class is not part of the JDK—it is part of the source code for the BeanBox.
See JarLoader.java in the beanbox/sun/beanbox directory of the BDK. The licensing of the
BeanBox code is very open.

Instantiating a Bean From a Serialized Stream


Loading serialized objects was discussed briefly in the Module 5,
‘‘Introspection.” It is done identically to the above examples, except for
one restriction. The beanClassName must resolve to a serialized object
found by replacing the periods with slashes and appending a .ser.

So an attempt to instantiate a bean named


sunw.demo.molecule.Molecule will first result in a search for
sunw/demo/molecule/Molecule.ser just in case a customized
version of the same bean exists locally.

Beans Outside of the BeanBox 10-37


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Roles of Class and ClassLoader

The Class Class


The Class class is, ironically, a class for representing and supporting
other classes. JavaBeans use the Class class to load a class of objects at
run-time.
Class myClass = Class.forName("sl291.dataTable.DataTableBean");

This method call accomplishes two important tasks in the beans


world:

● It loads a bean at runtime, given simply the name of the bean,


which can be very handy in keeping Java applications small in
size.

● It provides a class on which to call getClassLoader.


ClassLoader cl = (ClassLoader) myClass.getClassLoader();

Now the class loader object, cl, can be passed in as the first argument
of Beans.instantiate().

10-38 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Notes

✓ At some point in development, beans developers realize that the class loader almost
always returns null. It is a crime to pass null into Beans.instantiate because at a future
date the core classes may no longer return null. When the class loader is the JarLoader
from the BeanBox, for example, the class loader is the only means of obtaining a resource
such as a bean or an image from within a JAR file.

✓ The following functionality has been added to the Class class in JDK 1.1:

• Finds a resource given its name and returns a URL for it. See getContent for
information on pulling an ImageProducer, AudioClip, or InputStream from the URL.

URL getResource(String name)

• After obtaining the resource using getResource, open an input stream to it.

InputStream getResourceAsStream(String name)

Beans Outside of the BeanBox 10-39


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Roles of Class and ClassLoader

The ClassLoader Class

What Is It?

A class loader is a handler that knows how to load resources such as


serialized classes or bean objects, images, audio, and other data
formats. Class loaders help provide programs access to resources,
without burdening them with knowing the location and other details
of the resource.

What Can It Do?

The Applet Viewer has a built-in class loader that knows how to use
the APPLET, CODE, CODEBASE, and other HTML tags, attributes, and
parameters to load beans from JAR files or remote URLs.

The BeanBox has built-in utilities that include a class loader for beans
that exist in JAR files. The JDK 1.1.1 does not know how to load beans
directly from JAR files. This may change in the future.

10-40 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Notes

✓ Several methods have been added to the ClassLoader class in JDK 1.1.

• The following methods for ClassLoader work like the Class versions:

URL getResource(String name)

InputStream getResourceAsStream(String name)

• The methods below restrict the resources that can be loaded down to those present on
the system (local CLASSPATH, for example).

URL getSystemResource(String name)

InputStream getSystemResourceAsStream(String name)

Beans Outside of the BeanBox 10-41


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Sample Code

Instantiating a Bean in an Applet


Below is a full example of building an applet out of the Stock Market
beans example from Module 3. The HTML code is from a file called
testJar.html, which can be used to run the LabelChanger applet (shown
below) using the command appletviewer testJar.html.
✓ You can also run the applet in the HotJava 1.0 browser, which supports JDK 1.1 and
beans.

<APPLET
ARCHIVE="file:/home/BDK/jars/twoSimple.jar"
CODE="sl291.twoSimpleBeans.LabelChanger"
WIDTH=300
HEIGHT=100
></APPLET>

Here is the source code for the LabelChanger applet referenced in the
HTML code above. This applet (built manually) connects the MyText
and MyButton beans from Module 3 and displays them.
1 package sl291.twoSimpleBeans;
2
3 import java.awt.Frame;
4 import java.awt.BorderLayout;
5 import java.applet.Applet;
6 import java.beans.*;
7 import java.io.*;
8
9 public class LabelChanger extends Applet {
10 public void init() {
11 MyButton myButton = null;
12 MyText myText = null;
13 try {
14 ClassLoader cl = this.getClass().getClassLoader();
15 myText = (MyText) Beans.instantiate(cl,
16 "sl291.twoSimpleBeans.MyText");
17 myButton = (MyButton) Beans.instantiate(cl,
18 "sl291.twoSimpleBeans.MyButton");
19 } catch (Exception e) {
20 throw new Error(e.toString());
21 }

10-42 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Sample Code

Instantiating a Bean in an Applet (Continued)


22 myText.addLabelListener(myButton);
23 setLayout(new BorderLayout());
24 add("Center", myText);
25 add("South", myButton);
26 }
27
28 public static void main(String args[]) {
29 Frame f = new Frame("Label Changer Application");
30 LabelChanger labelChanger = new LabelChanger();
31 f.setLayout(new BorderLayout());
32 f.add("Center",labelChanger);
33 labelChanger.init();
34 f.setSize(300,100);
35 f.setVisible(true);
36 }
37
38 } // class LabelChanger
✓ Note that myButton is added as a listener to myText. If you look at the code for the
MyButton bean, it implements the LabelListener interface and defines the changeLabel
method.

✓ Note that the code shown here can be run as an application or as an applet.

Beans Outside of the BeanBox 10-43


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Sample Code

Instantiating a bean in an Application

Using Beans Located as System Resources Through CLASSPATH

Through clever construction, the previous LabelChanger applet can be


used not only as an applet but also as an application started from the
following command:
% java sl291.twoSimpleBeans.LabelChanger

Using a Bean in a JAR File

Notice that the LabelChanger applet or application used


this.getClass().getClassLoader() as its ClassLoader argument
to Beans.instantiate(). The method call will return a valid and
capable class loader when this is an applet, but it will return null for
an application. As was mentioned earlier in the module, the BeanBox’s
JarLoader or another Jar-capable class loader must be employed.

10-44 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Sample Code

Instantiating a Bean in an Application

JarLoader Example

Below is a generic JAR testing application that shows how the JAR
loader can be used. See the comments for usage instructions.
1 import java.awt.*;
2 import java.beans.*;
3 import java.io.*;
4 import sun.beanbox.*;
5
6 /**
7 * Usage: java JarBeanTest beanName jarFileName
8 * Where beanName is a fully qualified class like
9 * “sunw.demo.jelly.JellyBean”, or it is a serialized file named like:
10 * “serFiles.redJellyBean” for serFiles/redJellyBean.ser or
11 * often “sunw.demo.jelly.JellyBean” for sunw/demo/jelly/JellyBean.ser
12 * if the JAR package includes one.
13 *
14 * Note: This test program was written to test pulling stuff out of a
15 * JAR file, but it is important to note that because it’s an
application
16 * anything within CLASSPATH will be found too. If the program were
17 * modified so jar files were optional then it could be made to look
18 * exclusively at local and system files.
19 *
20 * Note also that this is very much an academic exercise because the
21 * AppletLoader already understands JARs with ARCHIVE tag and
serialized
22 * objects with OBJECT tag. The BeanWrapper with BDK uses AppletLoader
23 */
24 public class JarBeanTest extends Frame {
25 JarLoader jl;
26 JarInfo ji;
27
28 public Component loadBeanFromJar(String beanClassName,
29 String jarFileName) {
30
31 try {
32 jl = new JarLoader(jarFileName);
33 if (jl == null) {

Beans Outside of the BeanBox 10-45


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
34 System.err.println("file name passed is not a valid
JarFile");
35 return null;
36 }
37 } catch (Exception ex) {
38 System.err.println("caught an exception while trying to load"
39 +jarFileName);
40 ex.printStackTrace();
41 return null;
42 }

10-46 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Sample Code

Instantiating a Bean in an Application

JarLoader Example

43 ClassLoader cl = jl.getLoader();
44 // Ok, loaded all the classes -- now, instantiate *the requested
one*
45
46 ji = jl.loadJar();
47
48 try {
49 // We can either get an instance of one of the entities in
the archive
50 // (not the right thing to do for a bean but interesting)
51 //return (Component) ji.getInstance(beanClassName);
52
53 // Or we can instantiate a specific bean from the archive
54 // This should work for both ser and class versions of a bean
55 return (Component) Beans.instantiate(cl,beanClassName);
56
57 } catch (Exception e) {
58 System.err.println("Error instantiating "+beanClassName);
59 e.printStackTrace();
60 return null;
61 }
62 }
63
64 public static void main (String args[]) {
65 JarBeanTest me = new JarBeanTest();
66
67 Component myBean = me.loadBeanFromJar(
68 args[0], // bean class name
69 args[1]); // jar file name
70
71 me.add(myBean);
72 me.pack();
73 me.setVisible(true);
74 }
75 }

Beans Outside of the BeanBox 10-47


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Notes

10-48 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10

Hooking Beans Together

You saw in the LabelChanger how an applet or application can be


written to hook beans together. Think back to Module 2 in which the
BeanBox was used to hook the MyText and MyButton beans together.

What code did the BeanBox need to generate? When you hook beans
together, you must write code similar to that generated by the
BeanBox.

Beans Outside of the BeanBox 10-49


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Hooking Beans Together

It may not be obvious from looking at the code presented on


page 37, but there are three distinct phases represented by the code.

1. The beans are instantiated.


1 myText = (MyText) Beans.instantiate(cl,"sl291.twoSimpleBeans.MyText");
2 myButton = (MyButton) Beans.instantiate(cl,
3 "sl291.twoSimpleBeans.MyButton");

2. Beans that want to be listeners for another bean’s events must be


added as listeners to those source beans.
myText.addLabelListener(myButton);

3. The beans that visually display (all beans but invisible ones)
must be registered with the layout manager so they will be
visible.
1 setLayout(new BorderLayout());
2 add("Center", myText);
3 add("South", myButton);

10-50 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Exercise objective – The objective of this exercise is to give you


experience writing applets or applications that use the beans you
created in previous exercises. You will write a Java applet that
connects the DataClient to the DataEventMultiplexer, and the
DataEventMultiplexer to the three types of DataTableBean beans. The
applet will deliver the same configuration of the beans as you created
in the BeanBox to display stocks in a table with legend information.

Preparation
To be prepared for this exercise, you should have completed the
DataClient, DataEventMultiplexer, and DataTableBean beans from
previous lab exercises. If any of the code for these beans is incomplete,
use the solutions from the appropriate lab directories to complete your
beans.

Beans Outside of the BeanBox 10-51


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Writing the Applet

Skeleton code is provided for the TableApplet applet in the


SL291files/work directory as well as a TableApplet.html file for
testing the applet in the HotJava browser.

1. Change to the SL291files/work directory.

2. Compile the skeleton applet:

% jam -sjf=browser.jam

3. Test the applet in the HotJava browser by loading the


TableApplet.html file provided in the packages directory.

Notice the use of Label placeholders within a GridBag layout.


The AWT code is provided for you. Your task is to add code to
instantiate, configure your beans, and replace the Label
components with your beans.

4. Read the comments in the source code of the file


TableApplet.java.

10-52 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Writing the Applet (Continued)

5. Edit TableApplet.java and write the code necessary to


instantiate and connect the DataClient to the
DataEventMultiplexer bean and the DataEventMultiplexer to the
three DataTableBean beans.

6. Modify the TableApplet.html file to use the ARCHIVE tag to


specify all the .jar files needed to find the classes the
TableApplet applet uses.

Note – You can specify more than one JAR file with the ARCHIVE tag
by using a comma-separated list of JAR files, enclosed in double
quotes: ARCHIVE="../jars/first.jar,../jars/second.jar".

Beans Outside of the BeanBox 10-53


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Testing Your Solution

1. Recompile TableApplet.java and regenerate the


tableBrowser.jar file.
% cd SL291files/work
% jam -sjf=browser.jam

2. Make sure your DataServer beans from Module 9 are running. If


not, restart them.
% java sl291.rmilab.DataServer&

3. Set up the following security preferences in the HotJava browser:

▼ Choose Edit ➤ Preferences ➤ Applet Security.

▼ Select Medium for the Default setting for Unsigned Applets


and click on Apply.

4. Load the TableApplet.html file into the HotJava browser and


verify that the DataClient bean can send data to the
DataTableBeans.

10-54 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Optional—Using Serialized Beans

Here you will use the BeanBox to create .ser files of the three
different types of DataTableBeans and then use the .ser files in your
applet to instantiate these beans.

1. From the BeanBox, create an instance of a DataTableBean.

2. Use the PropertySheet window to set the number of rows to 8


and the number of columns to 1.

3. Using File ➤ SerializeComponent, save the bean to


SL291files/work/sl291/tableBrowser/
DataTableBeanHours.ser.

4. Modify the DataTableBean: use the PropertySheet window to set


the number of rows to 1 and the number of columns to 5.

5. Using File ➤ SerializeComponent, save the bean to


SL291files/work/sl291/tableBrowser/
DataTableBeanDays.ser.

6. Modify the DataTableBean: use the PropertySheet window to set


the number of rows to 8 and the number of columns to 5.

Beans Outside of the BeanBox 10-55


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Optional—Using Serialized Beans (Continued)

7. Using File ➤ SerializeComponent, save the bean to


SL291files/work/sl291/tableBrowser/
DataTableBeanPrices.ser.

8. Copy TableApplet.java to TableAppletCustom.java and


modify the code. TableAppletCustom.java will instantiate the
serialized objects (using the .ser files you created) instead of the
generic DataTableBean beans. (Remove the unnecessary property
settings for rows and columns.)

9. Modify tableBrowser.jam:

▼ Add TableAppletCustom.java to the classes variable.

10-56 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Optional—Using Serialized Beans (Continued)

10. Re-create the tableBrowser.jar file and compile


TableAppletCustom.java:

% jam -sjf=browser.jam

11. Copy TableApplet.html to TableAppletCustom.html and


change the CODE attribute to the TableAppletCustom.class
class.

12. Load TableAppletCustom.html into the HotJava browser and


test that the beans work.

Beans Outside of the BeanBox 10-57


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Optional—Creating an Application From the Applet

1. Examine the code for JarBeanTest that was presented in the


lecture. The code can be found in the directory
SL291files/mod10-outsideBB/course_examples. Become
familiar with what it does differently with the class loader than
what is used in the Beans.instantiate() method.

Note – JarBeanTest is an application that uses a JAR loader to load


beans from JAR files. The typical way an application loads beans is
through use of CLASSPATH directly to access the .class files; this relies
on Beans.instantiate using the system or local class loader
facilities.

2. Create the application TableBrowser.java using either of the


methods below:

▼ Copy TableApplet.java to TableBrowser.java, updating


the class name and using a main() method to instantiate a
Frame and add the applet to it.

▼ Modify the applet to extend Frame and work from there.

Note – The solution to this exercise currently does not implement the
JAR loader used in the JarBeanTest application.

10-58 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Tasks

Optional—Creating an Application From the Applet (Continued)

3. Compile and test the application:


% cd SL291files/work
% javac sl291/tableBrowser/TableBrowser.java
% java sl291.tableBrowser.TableBrowser

4. Verify that your application can select and display weeks of stock
just like the applet did.

Beans Outside of the BeanBox 10-59


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Exercise: Writing Applets or Applications With Beans

Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course.” You might find you do not have time to spend on discussion.
Then just highlight the key concepts students should have learned from the lab exercise.

● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.

● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.

● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.

● Applications
✓ Explore with the students how they might apply what they learned in this exercise to
situations back at their jobs.

10-60 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Assess the use of the BeanBox as a minimal environment for


testing and using beans.

❑ What do you need to do to create an applet or application using


existing bean components?

❑ List and provide examples of the various scenarios for building


beans.

❑ How can digital signatures be used to make an “official” bean?

❑ Create an applet that uses existing bean components and run it in


the Applet Viewer.

Beans Outside of the BeanBox 10-61


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
10
Think Beyond

You have seen in this module how beans are built, how they are
assembled into applets and applications, and how they are delivered.
You have seen the specific connecting code that is required to glue
these beans together.

Builder tools were mentioned and how they can off-load some of the
tedious coding required was described briefly.

In the next module, you will see a broader display of the sort of tools
that are becoming available to enable the use of beans in the business
environment. You will also get a preview of what current and future
advances will make beans even easier to use and even more attractive
as part of your enterprise solutions.

10-62 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Business Environment for
JavaBeans 11

Course Map
Application developers are more productive working in environments
that provide them with the programming tools and mechanisms
necessary to build, test, debug, and modify code. This module reviews
component-based software and discusses the programming
environments available for JavaBeans component development.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

11-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Relevance

Discussion – After working in the BeanBox to test your Bean


components, how would you rate the BeanBox as a development tool?
How easy is it to create applets, applications, or other JavaBeans
components? What more do you need in a business development
environment?

✓ The BeanBox provided with the BDK is not a true development environment—it is not
intended as such. You cannot generate the code for an applet, application, or another
Bean component within the BeanBox. The BeanBox is meant only as a testing
environment and as a reference base. A true development environment would provide
mechanisms for choosing whether you are building an applet, application, or Bean
component, providing visual tools to aid in this endeavor, generating source code for you,
possibly providing mechanisms for you to edit or add source code, providing the means
to test and debug what you are building, and then delivering the final, functioning
product—your Bean, applet, or application.

11-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Objectives

Upon completion of this module, you will be able to:

● Appraise how JavaBeans changes the “write once, run


everywhere” capability of the Java Platform.

● Identify and describe the three major elements of component-


based software.

● Compare and contrast rapid application development (RAD) and


integrated development environment (IDE) software with regard
to component development.

● Describe how JavaBeans interface with other component models


such as ActiveX/OLE/COM and OpenDoc.

● Defend the use of application builder tools for Bean component


development.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● Listing of builder tools that support the JavaBeans model at


http://splash.javasoft.com/beans/tools.html

● Component-Based Software with JavaBeans and ActiveX. [White


paper]. Available:
http://www.sun.com/javastation/whitepapers/javabeans/
javabean_ch1.html [1996, October].

Business Environment for JavaBeans 11-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

“Write once, run anywhere”

The phrase “write once, run anywhere”SM is associated with the Java
programming language since this language is a platform-independent,
object-oriented programming environment. With the JavaBeans API
packaged as part of the Java Platform, a component model is added to
the Java environment. JavaBeans components integrate into a variety
of containers, as well as being used as independent Java applets and
applications. They are portable and highly reusable in the broadest
number of containers and environments. Hence, the “write once, run
anywhere” Java phrase has become “write once, run anywhere, reuse
everywhere” for JavaBeans components.

In addition, with the coming of the Java Platform for the Enterprise,
president of JavaSoft, Alan Baratz, noted at JavaOne Developer
Conference in April, 1997 that the Java technology is extending to
enterprise infrastructures. This initiative includes Enterprise JavaBeans
and services that will make it far easier to do enterprise-wide Java
applications.
✓ For more information regarding the Enterprise Java initiative, see http://www.javasoft
.com/features/1997/april/enterprise.html.

11-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Component-Based Software Review

Recall that component-based software is a software model, an


architecture, and APIs, wherein software components are combined
dynamically to create an application.

Business Influences
The corporate computing environment is changing, influenced by the
competitive and economic pressures of the marketplace.
Heterogeneous intranets and Internet connectivity are becoming
realities for many companies. Companies are seeking to reduce costs
and create applications that are easily portable to the different
platforms on their intranets/Internets. Applications that are platform
independent are becoming a requirement.

Business Environment for JavaBeans 11-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Component-Based Software Review

Business Influences (Continued)


The Java programming environment has offered Web-based
computing solutions that reduce cost, as well as providing
applications that are platform independent. Component-based
software adds reusability of modular code pieces, further reducing
costs and time for application development. As companies look to the
future, component-based software and the Java technology will play a
key part in their computing decisions.

Major Elements
A component model consists of three major elements:

● Components – Software objects that include some program logic.


✓ Components vary in complexity, from simple buttons to full applications such as
spreadsheets.

● Containers – Software objects that are used to assemble


components.
✓ The JavaBeans BeanBox is a container for the JavaBeans component model. It provides a
context in which Beans can be arranged and interact.

● Scripting – A language or tool that provides the ability to initiate


and direct interactions between components.
✓ In the JavaBeans component model, the scripting language is Java. Other languages
include C/C++, Tcl/Tk, shell languages, and JavaScript™.

11-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Component-Based Software Review

Review of Services
Recall that all component-based software models and their APIs must
provide five basic services:

● Interface publishing and discovery

● Event handling

● Persistence

● Layout control

● Application builder support

JavaBeans is a component model, providing the services listed above


through introspection and the Reflection API, the delegation event
model, the Object Serialization API, the BeanBox, property sheets,
property editors, BeanInfo classes, and customizer classes.

Business Environment for JavaBeans 11-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Bridging JavaBeans to Other Component Models

In addition to the JavaBeans component model, there are other existing


component models in the industry, such as ActiveX, OpenDoc, and
LiveConnect. Through work with partners, JavaSoft will ensure that
JavaBeans are able to connect to these models using bridges.

With these bridges to other component models, JavaBeans components


will be portable to containers such as:

● Internet Explorer

● Netscape Navigator

● HotJava

● Delphi from Borland

● Visual Basic

● Word

● ClarisWorks

11-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Bridging JavaBeans to Other Component Models

ActiveX Bridge
The ActiveX bridge, which is available for download from JavaSoft,
provides users of legacy OLE/COM/ActiveX containers (Word or
Visual Basic, for example) with the ability to embed and use portable
JavaBeans components as if they were platform-specific
OLE/COM/ActiveX components.
✓ For more details on the ActiveX bridge, see http://splash.javasoft.com/beans/bridge/.

Note – The JavaBeans Migration Assistant for ActiveX is a tool from


IBM that converts ActiveX controls and generates JavaBeans, creating
a 100% Pure Java™ container. Sun™ is adopting the JavaBeans
Migration Assistant for ActiveX. Developers will be able to convert
ActiveX controls (platform-specific) to JavaBeans components
(platform-independent).

Business Environment for JavaBeans 11-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

InfoBus Technology

✓ Details on the InfoBus technology can be found at http://kona.lotus.com/21c2.html.

✓ Sun is also considering a proposal for an Object Aggregation/Delegation Model for future
releases of the Java programming language and JavaBeans. The draft specifications can
be found at http://splash.javasoft.com/beans/glasgow.html.

In an upcoming release of the Java Developer Kit (JDK), Sun plans to


include InfoBus technology from Lotus. This technology will enable
JavaBeans components to share and exchange information without
requiring additional programming. The InfoBus technology, written in
the Java programming language with no native code, will enable
developers to create applications capable of dynamic data exchange
and that still run on all Java Platforms.

11-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
InfoBus Technology

InfoBus Technology and JavaBeans


The InfoBus technology extends the JavaBeans specification. Through
enhanced interfaces provided by the InfoBus, JavaBeans components
can share and exchange dynamic data. This is in contrast to bound
properties in the JavaBeans specification, where data to be
communicated is hard-coded into the source and target components.

InfoBus Architecture Overview


There are three main components that compose an InfoBus
application:

● Data producers – Components that respond to requests for data


from consumers.

● Data Consumers – Components that are interested in hearing


about new data sets that enter the environment.

● Data controllers – An optional component that regulates or


redirects the flow of data between data producers and consumers.
✓ You can compare the InfoBus to a hardware bus with regard to data distribution.

Business Environment for JavaBeans 11-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Development Environments

Development environments and tools have been created to enable


programmers to build applications more quickly, as well as debug,
test, and modify them.

Integrated Development Environments


An integrated development environment (IDE) provides a suite of
tools to enable a developer to do many different development-oriented
tasks from one environment. A typical IDE consists of an intelligent
coded editor, a compiler, a debugger, and configuration management
support for multi-file builds of projects, and for revision control. The
real value-add for IDEs lies in how well integrated the pieces are.

One expects the modern day IDE to let a developer follow a project
build through a compile phase in which errors are output, through a
maintenance phase in which the developer can click on the “hot” text
of the errors to bring the trouble-spot into the editor, and on a more
intense debugging phase in which the developer steps through code
observing the program's operation to watch for problems.

11-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Development Environments

Rapid Application Development


A builder tool intended for rapid application development (RAD)
takes the IDE one step further. The major feature of a RAD tool is often
a visual GUI builder in which heavyweight components can be
dragged, dropped, and manipulated in a WYSIWYG (what you see is
what you get) environment until the developer is satisfied. At that
point, the developer presses a button and code is generated. RADs
often support various types of dialogs in which complex types of
applications are built from templates, with minimal interaction from
the developer. RADs are not limited to GUI builders. A database
application builder or a charting application builder can also be built
using RAD applications.

Recently, component-based development is carrying a trend toward


RAD environments in which no programming knowledge whatsoever
is required to produce an array of complex, component-rich
applications.

Business Environment for JavaBeans 11-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Visual Application Builder Tools

What Are They?


Visual application builder tools for components are development tools
that provide a visual interface for the developer in order to manipulate
components and modify their properties and behaviors. Such tools
will provide mechanisms such as tool palettes, inspectors, and editors
for working with components to assemble an application. Through
these mechanisms, you, the application developer, can modify the
state and appearance of components, establish relationships between
components, create new components, and generate applets or
applications.

11-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Visual Application Builder Tools

Examples
The following products have been announced as visual builder tools
that support the JavaBeans component model. Many of these tools are
advertised as RAD tools or environments. For specific information
about any of these tools, refer to the URL listed under "References" on
page -3.

● Java Workshop from Sun

The current version of Java Workshop (Version 2.0) enables you


to create applets or applications with easy-to-use Web-centric
development tools, a GUI builder, integrated toolset, publication
tools, and multi-platform support. The next generation of Java
Workshop will include features that support development of
JavaBeans components, editor syntax highlighting, remote
debugging, and integration of Sun JIT technology.

● Java™ Studio™ from Sun

Java Studio is a visual assembly, HTML authoring tool, with a


full complement of reusable components written entirely in Java.
End-users can visually create solutions to access, manipulate, and
publish information using the Internet, without writing any code.

Java Studio provides a set of JavaBeans business components


such as charting, graphing, database access, spreadsheets, white
boards, and chat components.

Business Environment for JavaBeans 11-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Visual Application Builder Tools

Examples (Continued)
● Mojo from Penumbra Software

The Mojo product is composed of two main parts: a Designer


with a GUI and a Coder that organizes Java objects and gives the
user direct access to all aspects of code. Advertised as a tool for
beginners or masters of the Java programming language, the two
parts can be viewed in this regard.

For beginners, the Designer provides what is necessary to create


applets or applications using the supplied library of professional
components with no coding necessary.

For master Java programmers, the Coder offers more control,


giving the developer access to underlying code for modification
of components, properties, or actions. In addition, a developer
can add new code or create new components.

● Visual Café from Symantec Corporation

A RAD tool, Visual Café enables you to assemble complete


JavaBeans, applets, and applications from a library of standard
and third-party JavaBeans, without writing source code. Visual
Café provides an Interaction Wizard that gives you the ability to
create interactions between objects, automatically generating the
Java code for you.

Visual Café is available for both Windows 95 and NT, as well as


for the Macintosh.

11-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Visual Application Builder Tools

Examples (Continued)
● JBuilder from Borland

Advertised as Borland’s professional visual RAD tool for Java,


JBuilder provides tools for customizing and extending the
JBuilder environment, drag-and-drop components, just-in-time
compiling, editing and debugging, and visually designing
applets and applications by modifying properties and event
handling.

A Project Expert is provided that helps you build a skeleton of


your project (applet or application) very quickly. Then, using the
other tools provided, you complete the details and design.

● VisualAge for Java from IBM®

VisualAge for Java is a Java RAD environment for connecting


thin Java clients to existing enterprise applications on the
Internet. VisualAge for Java is a programming environment that
assists in the more mundane tasks of application development
such as programming communication code, connecting the
Enterprise to the Web, and creation of user interface code.

Business Environment for JavaBeans 11-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11

Visual Application Builder Tools

Examples (Continued)
The tools mentioned here were some of the first tools described on the
JavaSoft Web site. Additional tools now include the following:

● SuperCede from Asymetrix

● JdesignerPro 2.0 from BulletProof Software

● Data Director for Java from Informix

● JavaPlan™ from Lighthouse Design

● Visual JavaScript (formerly Palomar) from Netscape

● Javadraw from SFS Software

● Cosmo Code from Silicon Graphics

● PowerJ (formerly Jato) from Sybase

● VisualAgeWebRunner™ Toolkit from Taligent

● Kawa from Tek-Tools

● Vision from Unify

11-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Visual Application Builder Tools

Deciding on the Tool for You


No one can decide which tool is best for you. You need to identify
what features you will require of a tool, what output you expect from
a tool (new components, applets, applications), how much control you
want, whether you will need to write code using the tool, and so forth.
Once you have determined your tool requirements, you will be better
able to evaluate the tools available and make a decision on the tool
that suits your needs.

Business Environment for JavaBeans 11-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Check Your Progress

Before continuing on to the next module, check that you are able to
answer the following:

❑ Appraise how JavaBeans changes the “write once, run


everywhere” capability of the Java platform.

❑ Identify and describe the three major elements of component-


based software.

❑ Compare and contrast rapid application development (RAD) and


integrated development environment (IDE) software with regard
to component development.

❑ Describe how JavaBeans interface with other component models


such as ActiveX/OLE/COM and OpenDoc.

❑ Defend the use of application builder tools for Bean component


development.

11-20 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
11
Think Ahead

What do you do if your Beans need to run in an environment that does


not support JDK 1.1?

Business Environment for JavaBeans 11-21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Transitional Beans
(Optional) 12

Course Map
Until browsers and other applications support JDK 1.1, you need to
write transitional Beans for use in these applications.

Introduction to JavaBeans

Overview of The Bean Event


The BeanBox
JavaBeans Model

Modifying and Persisting Beans

Bean Properties Introspection

Persistence Customization

Working With Beans

Event Adapters Distributed Computing


With Beans

Beans Outside of Business Environment


the BeanBox for JavaBeans

Optional

Transitional Beans

12-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Relevance

✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module.

Discussion – You have now created many different bean components


in the lab exercises. These beans are written based on JDK 1.1.
Consider the following questions:

1. You are designing bean components to be used in Java-enabled


browsers to provide some functionality to visitors of your Web
pages. What do you do about the fact that not all browsers
support JDK 1.1?
✓ To bridge the time gap between the FCS release of JDK 1.1 and when current Java
environments (such as browsers) support JDK 1.1, JavaSoft has provided guidelines for
creating beans that will run under JDK 1.0.2.

2. If you create beans that can run in JDK 1.0.2 applications, do


these beans need to be updated to run in JDK 1.1 environments?
✓ Beans that run in JDK 1.0.2 applications are fully compliant with the final JavaBeans
architecture as long as you created the beans following the developer rules provided in
Appendix A of the JavaBeans 1.0 specification. You should not need to update your beans
unless you plan to modify or add to the functionality of the bean.

12-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Objectives

Upon completion of this module, you will be able to:

● Define transitional beans.

● Explain when you might need to use transitional beans, especially


with regard to Browser support of JDK 1.1.

● Describe the developer rules and marker classes used in creating


transitional beans.

● Create a transitional bean.

References
Additional resources – The following references can provide
additional details on the topics discussed in this module:

● JavaBeans Under JDK1.0.1. [On-line]. Available:


http://splash.javasoft.com/beans/initial.html.

● Appendix A of the JavaBeans API 1.0 Specification. [On-line].


Available: http://splash.javasoft.com/beans/spec.html.

Transitional Beans (Optional) 12-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12

What Are Transitional Beans?

A transitional Bean is a bean that is fully compliant with the 1.0


JavaBeans architecture, but which runs on JDK 1.0.2 applications (such
as browsers).

Compatibility With JavaBeans FCS


Although transitional beans are fully compatible with JavaBeans first
customer ship (FCS) architecture, transitional beans use only a subset
of the full bean model. This subset includes the basic property,
method, and event mechanisms.

12-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
What Are Transitional Beans?

Browser Support for JavaBeans


Many existing browsers will be supporting the JDK 1.1 release in the
near future (if they have not already done so). Since the JavaBeans API
is part of the JDK 1.1 core, support for JavaBeans components will be
automatic at that time.

In the meantime, developers who want to create beans to run in JDK


1.0.2 supported browsers (or applications) should create transitional
beans.

Transitional Beans (Optional) 12-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12

Creating a Transitional Bean

When creating transitional beans, there are some concepts and


developer rules you must understand and follow in order to enable
your transitional beans to run under JDK 1.0.2 as well as JDK 1.1.

Marker Classes
The JavaBeans API (and JDK 1.1) uses certain classes or interfaces to
determine that a given class is intended to perform a given role. These
classes or interfaces are referred to as marker classes, and currently
include java.io.Serializable, java.util.EventListener, and
java.util.EventObject. To enable transitional beans to make use of
these markers for events and serialization, three transitional marker
classes are provided for transitional beans developers:
sunw.util.EventObject, sunw.util.EventListener, and
sunw.io.Serializable.

12-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Creating a Transitional Bean

Marker Classes (Continued)


When a transitional bean runs in a JDK 1.1 environment, the JDK 1.1
version of these transitional marker classes is used. Since these JDK 1.1
versions inherit from respective java.* classes in JDK 1.1, JDK 1.1
functionality is used.

Example

Suppose a transitional bean implements sunw.io.Serializable to


persist the state of the bean. When the bean is run under JDK 1.1, the
JDK 1.1 sunw.io.Serializable, which inherits from
java.io.Serializable, is used. So your transitional bean uses JDK
1.1 serialization.

Transitional Beans (Optional) 12-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12

Creating a Transitional Bean

Developer Rules
If you, as a bean developer, want your transitional beans to work
correctly under JDK 1.1, you need to adhere to the following rules for
creating transitional beans:

● The bean must be delivered in a bean JAR or zip file.


✓ JDK 1.0.2 does not provide a JAR utility. After you compile your transitional beans under
1.0.2, you can create a JAR file using the JDK 1.1 jar command and a temporary MANIFEST
file (see the manifest.tmp file in the student lab files mod12-transitional directory). The
syntax is:

jar cfm jarFileName manifest.tmp packageNameAsPath/*.class

✓ Whomever receives your JAR file must be able to extract the classes (jar xvf
jarFileName) or use the JAR file directly in their application.

✓ A zip file can be created using the zip command (a free software utility). The zip file must
be created without using compression. On a UNIX platform, this implies using the -0
option.

● The bean must use the getFoo() and setFoo() patterns for
properties, as defined in the JavaBeans 1.0 specification.

● All of the bean's persistent state must be accessible using


getFoo() and setFoo() properties. This allows external tools to
save and restore the state of the bean using the property accessor
methods.

There is one exception to this rule. A bean can ignore state in


java.awt base classes.

12-8 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Creating a Transitional Bean

Developer Rules (Continued)


● Any events the bean fires must use the new AWT event model and
should use the sunw.util.EventObject and
sunw.util.EventListener interfaces to mark events and event
listeners. However, in interacting with AWT, the bean must of
necessity use the old AWT event model to catch AWT events.
✓ See the code example on page 14. When catching events, the old AWT event methods (in
this case handleEvent()) are used. When firing events and informing listeners of events,
use the new event model.

● If the bean is prepared in the future to use automatic serialization,


then it must inherit from the sunw.io.Serializable marker
interface.
✓ Refer to the code example on page 13 to see how this is done.

● The bean cannot rely on any new 1.1 interfaces.


✓ At the time of this writing, JAR file formats are not understood in the Netscape Navigator
3.01 browser.

✓ The HotJava 1.0 beta browser, however, is able to run applets from an HTML file that uses
a JAR or zip file as the value of the ARCHIVE parameter.

Transitional Beans (Optional) 12-9


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

Sample Description
Figure 12-1 shows an applet running in the Netscape Navigator 3.01
browser. The applet contains two simple transitional beans: a button
bean and a jellybean bean. The button fires a pushButtonEvent when
clicked, which causes the jellybean to change its color from green to
blue.

Figure 12-1 An Applet Composed of Transitional Beans

✓ The 3.01 version of the Netscape Navigator browser supports JDK 1.0.2. This applet also
runs in the HotJava 1.0 beta browser, which supports JDK 1.1.

12-10 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

The code for the example shown on page 10 is part of a downloadable


zip file available at
http://splash.javasoft.com/beans/initial.html. The code
illustrates how the three transitional marker classes are used, as well
as how to deal with events (catching them with JDK1.0.2 methods and
firing them as new style events).
✓ The files contained in the downloadable zip file have been installed as part of the
student’s lab files in the mod12-transitional directory. The zip file includes the
transitional marker classes, which must be part of CLASSPATH when you compile your 1.0.2
beans under JDK 1.0.2.

ButtonPushEvent Class
The ButtonPushEvent class extends the marker class
sunw.util.EventObject to comply with event objects under JDK 1.1.
The following code creates a new event type:
1 package demo;
2
3 /**
4 * JDK1.1 Event Model
5 * This class describes the event that gets generated when
6 * OurButton gets pushed.
7 */
8
9 public class ButtonPushEvent extends sunw.util.EventObject {
10 public ButtonPushEvent(java.awt.Component source) {
11 super(source);
12 }
13 }

Enter these lines into a file called ButtonPushEvent.java.


✓ It might be necessary to go over with students how packages are used in Java. It is
recommended that all beans be contained in packages. Note that all demo beans provided
with the BDK do so.

Transitional Beans (Optional) 12-11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

Listener Interface
The following interface extends the marker class
sunw.util.EventListener for compliance with the new JDK 1.1
event model for sources and listeners.

In JDK 1.1, a button listener would implement an ActionListener


interface, add itself as a listener using addActionListener(), and
define the required actionPerformed() method. These listener
interfaces and mechanisms do not exist under JDK 1.0.2, so you define
your own listener interface.
1 package demo;
2
3 /**
4 * This interface describes the method that gets called when
5 * an OurButton gets pushed.
6 */
7
8 public interface ButtonPushListener extends sunw.util.EventListener
{
9 public void push(ButtonPushEvent e);
10 }
✓ This indicates that a listener that implements ButtonPushListener must add itself as a
ButtonPushListener and define a push() method that will receive a ButtonPushEvent when
a button is clicked.

12-12 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

OurButton Class
In JDK 1.1, buttons are already defined as a source of an ActionEvent
event object. For beans in JDK 1.0.2, you must indicate that your
button is a source for ButtonPushListener that you defined on page
12. This means you define addButtonPushListener() and
removeButtonPushListener() methods for listeners to use.
1 package demo;
2
3 /**
4 * The OurButton class is a very minimal Bean that simply extends the
5 * standard JDK 1.0.2 Button class to throw a Bean event.
6 */
7
8 import java.util.Vector;
9 import java.awt.*;
10
11 public class OurButton extends java.awt.Button implements
12 sunw.io.Serializable {
13 private boolean dbg;
14 private Vector listeners = new Vector();
15
16 public OurButton() {
17 this("press");
18 }
19
20 public OurButton(String label) {
21 super(label);
22 }
23
24 // Register an Event Listener.
25 public synchronized void addButtonPushListener(ButtonPushListener
26 bl) {
27 listeners.addElement(bl);
28 }
29 // Remove an Event Listener.
30 public synchronized void removeButtonPushListener(ButtonPushListener
31 bl) {
32 listeners.removeElement(bl);
33 }

Transitional Beans (Optional) 12-13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

OurButton Class (Continued)


The remainder of the code in the OurButton class catches an event
generated by a button click under JDK 1.0.2, which generates a JDK 1.1
compliant event using the ButtonPushEvent() method defined on
page 11, and for all ButtonPushListeners, calls the method that is
defined to handle the event (push()).
34
35 // Catch an old style AWT event and fire it as a new style event.
36
37 public boolean handleEvent(Event evt) {
38 if (evt.id == Event.ACTION_EVENT) {
39
40 // Notify each of our listeners.
41 Vector l;
42 ButtonPushEvent e = new ButtonPushEvent(this);
43 synchronized(this) {
44 l = (Vector) listeners.clone();
45 }
46
47 for (int i = 0; i < l.size(); i++) {
48 ButtonPushListener bl =
49 (ButtonPushListener)l.elementAt(i);
50 bl.push(e);
51 }
52
53 }
54 return super.handleEvent(evt);
55 }
56
57 public boolean isDebug() {
58 return dbg;
59 }
60
61 public void setDebug(boolean x) {
62 dbg = x;
63 }
64 }

12-14 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

JellyBean Class
Below is the code for the JellyBean bean. It does not generate any
events; that is, it is not a source, so it does not require the event
mechanisms implemented in the OurButton class.
1 package demo;
2 /**
3 * A very simple example Bean.
4 *
5 * We have a screen appearance that is a color oval, and we have one
6 * property "color".
7 */
8
9 import java.awt.*;
10
11 public class JellyBean extends Canvas implements
12 sunw.io.Serializable {
13
14 public JellyBean() {
15 resize(60,40);
16 }
17
18 public void paint(Graphics g) {
19 g.setColor(ourColor);
20 g.fillArc(5, 5, 30, 30, 0, 360);
21 g.fillArc(25, 5, 30, 30, 0, 360);
22 g.fillRect(20, 5, 20, 30);
23 }
24
25 public Color getColor() {
26 return ourColor;
27 }
28
29 public void setColor(Color newColor) {
30 ourColor = newColor;
31 repaint();
32 }
33
34 private Color ourColor = Color.orange;
35 }

Transitional Beans (Optional) 12-15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

Flipper Applet
In the code below, an applet is defined as a listener for the button (it
implements ButtonPushListener interface).
✓ Remind students that implementing the ButtonPushListener interface implies that the
applet will define the push() method to handle a ButtonPushEvent.

1 package demo;
2
3 /**
4 * A very simple demo applet that uses the "OurButton" Bean
5 * and the "JellyBean" Bean.
6 *
7 * We catch "ButtonPush" events from the button and then change the
8 * color on the target JellyBean.
9 */
10
11 import java.awt.Color;
12
13 public class Flipper extends java.applet.Applet implements
14 ButtonPushListener {
15
16 public void init() {
17
18 // We do our own hand layout.
19 setLayout(null);
20
21 // Create a JellyBean.
22 jb = new JellyBean();
23 jb.setColor(firstColor);
24 add(jb);
25 jb.reshape(250, 25, 100, 40);
26
27 // Create a button.
28 btn = new OurButton();
29 btn.setLabel("flip");
30 add(btn);
31 btn.reshape(100, 30, 100, 30);
32
✓ Note that although the JavaBeans 1.0 specification recommends that you use
Beans.instantiate() to create a Bean; this is not possible under 1.0.2 since
Beans.instantiate() does not exist.

12-16 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Example of Transitional Beans

Flipper Applet (Continued)


In the remainder of the code for the applet, the applet adds itself as a
listener to the button bean and defines what will happen when the
button is clicked (that is, change the color of the JellyBean bean).
33 // Add ourself as an event handler object for button pushes.
34 btn.addButtonPushListener(this);
35 }
36
37 /**
38 * This methods catches a button push event and uses it to
39 * flip the color off our JellyBean between two choices.
40 */
41
42 public void push(ButtonPushEvent evt) {
43 if (jb.getColor() == firstColor) {
44 jb.setColor(secondColor);
45 } else {
46 jb.setColor(firstColor);
47 }
48 }
49
50 private Color firstColor = Color.green;
51 private Color secondColor = Color.blue;
52 private JellyBean jb;
53 private OurButton btn;
54 }

Transitional Beans (Optional) 12-17


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12

Things to Remember

When you create JDK 1.0.2 beans using JDK 1.0.2 AWT components,
you need to do the following:

● Define a JDK 1.1 compliant event X that the JDK 1.0.2 component
will generate.

● Define a listener interface Y with the name of the method Z that it


will use.

● Define your AWT component as a source for event X. This implies


defining addYListener and removeYListener methods.

● Catch the usual JDK 1.0.2 events for your AWT component and
generate event X.

● Notify all your listeners of the event X. This means that for all
listeners, you will call method Z.

● Define a listener. This means implementing interface Y, calling


AWTcomponent.addYListener(), and defining method Z to act
on event X.

12-18 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
12
Check Your Progress

Check that you are able to do the following:

❑ Define transitional beans.

❑ Explain when you might need to use transitional beans.

❑ Describe the developer rules and marker classes used in creating


transitional beans.

❑ Create a transitional bean.

Transitional Beans (Optional) 12-19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Event 1.0.x to Event 1.1
Conversion A
This appendix gives an overview of the event handling under JDK
1.0.x and JDK 1.1 and provides a table that maps 1.0.x events and
corresponding methods to their 1.1 counterparts.

References
Additional resources – The contents of this appendix were obtained
from the Web page “How to Convert Programs to the 1.1 AWT API.”
[Online]. Available: http://www.javasoft.com/products/JDK/
1.1/docs/guide/awt/HowToUpgrade.html.

A-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
A
Event Handling

Event Handling Before JDK 1.1


Before 1.1, the Component handleEvent method (along with the
methods it called, such as the action method) was the center of event
handling. Only Component objects could handle events, and the
component that handled an event had to be either the component in
which the event occurred or a component above it in the component
containment hierarchy.

Event Handling in JDK 1.1


In 1.1, event handling is no longer restricted to objects in the
component containment hierarchy, and the handleEvent method is no
longer the center of event handling. Instead, objects of any type can
register as event listeners. Event listeners receive notification only
about the types of events they have registered their interest in. Never
again will you have to create a Component subclass just to handle
events.

When upgrading to the 1.1 release, the simplest way to convert event-
handling code is to leave it in the same class, and make it a listener for
that type of event.

Another possibility is to centralize event-handling code in one or more


non-component listeners (adapters or filters). This approach lets you
separate the GUI of your program from implementation details. It
requires that you modify your existing code so that the listeners can
get whatever state information they require from the components. This
approach can be worth your while if you are trying to keep your
program's architecture clean.

A-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
A
Converting 1.0 Event Handling to 1.1

The biggest part of converting most 1.0 AWT-using programs to the 1.1
API is converting the event-handling code. The process can be
straightforward, once you figure out which events a program handles
and which components generate the events. Searching for “Event” in a
source file lets you find the event-handling code.

Note – While you are looking at the code you should note whether
any classes exist solely for the purpose of handling events; you might
be able to eliminate such classes.

Table A-1 can be used in the conversion process to help map 1.0 events
and methods to their 1.1 counterparts.

● The first column lists each 1.0 event type, along with the name of
the method (if any) that is specific to the event.

Where no method is listed, the event is always handled in the


handleEvent method.

● The second column lists the 1.0 components that can generate the
event type.

● The third column lists the listener interface that helps you handle
the 1.1 equivalents of the listed events.

● The fourth column lists the methods in each listener interface.

Event 1.0.x to Event 1.1 Conversion A-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
A

Table 1-1 Event Conversion Table

1.0.x 1.1

Event/Method Generated by Interface Methods


Button
ACTION_EVENT/action List ActionListener actionPerformed(ActionEvent)
MenuItem
TextField

Checkbox
CheckboxMenuItem ItemListener itemStateChanged(ItemEvent)
Choice

WINDOW_DESTROY windowClosing(WindowEvent)
WINDOW_EXPOSE Dialog WindowListener windowOpened(WindowEvent)
WINDOW_ICONIFY Frame windowIconified(WindowEvent)
WINDOW_DEICONIFY windowDeiconified(WindowEvent)

windowClosed(WindowEvent)*a
windowActivated(WindowEvent)*
windowDeactivated(WindowEvent)*

componentMoved(ComponentEvent)
WINDOW_MOVED Dialog ComponentListener ComponentHidden(ComponentEvent)*
Frame componentResized(ComponentEvent)*
componentShown(ComponentEvent)*

SCROLL_LINE_UP
SCROLL_LINE_DOWN AdjustmentListener
SCROLL_PAGE_UP (Or use the new ScrollPane adjustmentValueChanged(AdjustmentEvent)
SCROLL_PAGE_DOWN Scrollbar class)
SCROLL_ABSOLUTE
SCROLL_BEGIN
SCROLL_END

A-4 Course Title


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1998
A
Table 1-1 Event Conversion Table (Continued)

1.0.x 1.1

Event/Method Generated by Interface Methods


Checkbox
LIST_SELECT CheckboxMenuItem ItemListener itemStateChanged(ItemEvent)
LIST_DESELECT Choice
List

Canvas
MOUSE_DRAG/mouseDrag Dialog mouseDragged(MouseEvent)
MOUSE_MOVE/mouseMove Frame MouseMotionListener mouseMoved(MouseEvent)
Panel
Window

MOUSE_DOWN/mouseDown Canvas mousePressed(MouseEvent)


MOUSE_UP/mouseUp Dialog mouseReleased(MouseEvent)
MOUSE_ENTER/mouseEnter Frame MouseListener moseEntered(MouseEvent)
MOUSE_EXIT/mouseExit Panel mouseExited(MouseEvent)
Window mouseClicked(MouseEvent)*

KEY_PRESS/keyDown keyPressed(KeyEvent)
KEY_RELEASE/keyUp Component KeyListener keyReleased(KeyEvent)
KEY_ACTION/keyDown keyTyped(KeyEvent)*
KEY_ACTION_RELEASE/keyUp

GOT_FOCUS/gotFocus Component FocusListener focusGained(FocusEvent)


LOST_FOCUS/lostFocus focusLost(FocusEvent)

No 1.0 equivalent ContainerListener componentAdded(ContainerEvent)


componentRemoved(ContainerEvent)

No 1.0 equivalent TextListener textValueChanged(TextEvent)

a.

Course Title A-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1998
A
Making a Component a Listener

Follow the general steps below to convert a 1.0 component into a 1.1
listener.

1. Change the source file so that it imports the java.awt.event


package.
import java.awt.event.*;

2. Figure out which components generate each event type. Use


Table A-1 to help you.

For example, if you are converting event code that is in an


action method, you should look for Button, List, MenuItem,
TextField, Checkbox, CheckboxMenuItem, and Choice objects.

3. Change the class declaration so that the class implements the


appropriate listener interfaces as indicated in Table A-1.

For example, if you are trying to handle an action event


generated by a Button, Table A-1 tells you to implement the
ActionListener interface.
1 public class MyClass extends SomeComponent
2 implements ActionListener {

4. Determine where the components that generate the events are


created. Just after the code that creates each one, register this as
the appropriate type of listener.

For example:
newComponentObject.addActionListener(this);

A-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
A
Making a Component a Listener

5. Create empty implementations of all the methods in the listener


interfaces your class must implement. Copy the event-handling
code into the appropriate methods.

For example, ActionListener has just one method,


actionPerformed. As a shortcut way of creating the new
method and copying the event-handling code to it, you can
simply change the signature of an action method from this:
public boolean action(Event event, Object arg) {

to this:
public void actionPerformed(ActionEvent event) {

6. Modify the event-handling code in these ways:

a. Delete all return statements.

b. Change references to event.target to event.getSource().

c. Delete any code that unnecessarily tests which component


the event came from. (Now that events are forwarded only if
the generating component has a listener, you do not have to
worry about receiving events from an unwanted component.)

d. Perform any other modifications required to make the


program compile cleanly and execute correctly.

Event 1.0.x to Event 1.1 Conversion A-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Jamfile and Manifest
Templates B
This appendix contains the listing for the two templates used in some
of the labs of this course. They are already included in electronic form
in your existing environments, but are printed here for convenience.

B-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
B
Listing for Jamfile.template

1 include $(JAM_HOME)Jamrules ;
2 # set the name of the JAR file
3 jar = JAR_FILE_NAME.jar ;
4 # this sets the package name of the java files - this is used
5 # to check dependencies of all compiled classes
6 SetPackage sl291 seperate components with spaces ;
7 # list of java sources - if the files are in the package
8 # directory then set the global variable
9 # $(USE_FULL_PATH_FOR_SOURCE) to "TRUE"
10 classes = File1.java
11 File2.java ;
12 DEPENDS all : $(jar) ;
13 # add the package of the java files to the list of directories
14 # added to the JAR file
15 AddPackageToJar $(CURR_PACKAGE) ;
16 # set the manifest file name - manifest.tmp is normally used
17 SetManifest manifest.tmp ;
18 # build the JAR file
19 JarFile $(jar) : $(classes) ;
20 # copy the new jar file to the BDK jars directory
21 File $(BDK_JARS_DIR)$(SLASH)$(jar) : $(jar) ;

B-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
B
Listing for manifest.tmp

1 Manifest-Version: 1.0
2 Name: sl291/package/classname1.class
3 Java-Bean: True
4 Name: sl291/package/classname2.class
5 Java-Bean: True

Jamfile and Manifest Templates B-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
JAM Overview C
This appendix gives an overview of the JAM make utility used to
produce beans components in this class.

References
Additional resources – Complete JAM documentation is available
from Perforce’s web site at
http://www.perforce.com/jam/jam.html.

C-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
JAM

Features
● Jam/MR is a make(1) replacement that makes building
uncomplicated things simple and building complicated things
manageable.

● Jam/MR's language is expressive, making Jamfiles (c.f. Makefiles)


compact. Here's a sample:

Main smail : main.c map.c resolve.c deliver.c


misc.c parser.y alias.c pw.c headers.c
scanner.l getpath.c str.c ;

● This builds "smail" from a dozen source files. Jam/MR handles


header file dependencies automatically and on-the-fly.

● Jam/MR is very portable: it runs on UNIX, VMS, NT, OS/2, and


Macintosh MPW. Most Jamfiles themselves are portable, like the
sample above.

● Jam/MR is unintrusive: it is small, it has negligible CPU overhead,


and it does not create any of its own unusual files (c.f. Odin,
nmake, SunOS make).

● Jam/MR can build large projects spread across many directories in


one pass, without recursing, tracking the relationships among all
files. On UNIX and NT, jam can do this with multiple, concurrent
processes.

● Jam/MR is not under the GNU copyright, so you can incorporate


it into commercial products.

● The JAM distribution ships with complete source code and


documentation and is distributed for free from the web site of
Perforce.

C-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
Custom JAM Rules for Java Programs

JAM ships with complete rules for compiling programs with C, C++,
Fortran, and other languages, but does not currently include rules for
producing Java applications. Special build rules were added to the
rules provided with the distribution. These special rules are provided
below. To use them, you must add them to the end of the Jambase file
in the build directory before building JAM.
# @(#)Jamrules1.83 97/12/22
#
# Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software
# and its documentation for NON-COMMERCIAL purposes and without
# fee is hereby granted provided that this copyright notice
# appears in all copies. Please refer to the file "copyright.html"
# for further important copyright and licensing information.
#
# SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
# THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
# TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
# ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
# DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
#
#
# Jam rule file
#
# For this file to work correctly the following environment variables must be
# defined:
# JAVA_HOME - the root directory of the JDK (does not end in slash)
#
# The BDK is assumed to be in $(JAVA_HOME)/BDK. If not then invoke the SetBdkHome
# rule to set the JAM variable $(BDK_HOME) and $(BDK_JARS_DIR) to the proper
# values.
# Variable definitions
if $(UNIX) {
JAVA_HOME?= /usr/local/jdk1.1 ;
JAVAC = $(JAVA_HOME)/bin/javac ;
JAR = $(JAVA_HOME)/bin/jar ;
if ! $(BDK_HOME) {
BDK_HOME = $(JAVA_HOME)/BDK ;
}
BDK_JARS_DIR = $(BDK_HOME)/jars ;
} else if $(NT) {
ECHO "On NT ..." ;
JAVA_HOME ?= C:\\jdk1.1 ;
JAVAC = $(JAVA_HOME)\\bin\\javac ;
JAR = $(JAVA_HOME)\\bin\\jar ;
if ! $(BDK_HOME) {

JAM Overview C-3


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
Custom JAM Rules for Java

BDK_HOME = $(JAVA_HOME)\\BDK ;
}
BDK_JARS_DIR = $(BDK_HOME)\\jars ;
}
#javac and jar command-line flags
JCFLAGS = ;
JAR_OPTIONS = -cvf ;
DESTDIR ?= .$(SLASH) ;
ECHO "Java compiler is at: "$(JAVAC) ;
ECHO "Destination directory is: "$(DESTDIR) ;
#if TRUE then the relative path of JAVA source files is created using the package
#information - otherwise it is assumed the source files are in the current directory
USE_FULL_PATH_FOR_SOURCE = FALSE ; # TRUE if source files are located in a
# subdirectory equivalent to the package
PACKAGE_PATH = ; # the current package in dot notation
CURR_PACKAGE = ; # the current package of java source files being processed
JAR_MEMBERS = ; # non-class and non-manifest files to be placed in a JAR file
# such as serialized objects, image, or html files
JAR_DIRS = ; # the list of all of the directories to be recursively placed
# in the JAR file
MANIFEST = " " ; # the name of the manifest file to be included in the JAR file
CLASS_FILES = ; # a list of all of the class files to be generated
# General rules and actions
# this rule resets all global variables used by the java rules used to generate
# classes and JAR files
rule Reset_Java_Rules
{
JCFLAGS = ;
JAR_OPTIONS = -cvf ;
DESTDIR ?= .$(SLASH) ;
USE_FULL_PATH_FOR_SOURCE = FALSE ;
CURR_PACKAGE = ;
PACKAGE_PATH = ;
JAR_MEMBERS = ;
JAR_DIRS = ;
MANIFEST = " " ;
CLASS_FILES = ;
}
# changes the jar tool options to the target value
rule SetJarOptions
{
JAR_OPTIONS = $(<) ;
}
# sets the name of the manifest file and adds the proper option to the jar tool
# option flags
rule SetManifest
{
MANIFEST = $(<) ;
JAR_OPTIONS = $(JAR_OPTIONS)m ;
ECHO JAR option flags changed to $(JAR_OPTIONS) ;

C-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
Custom JAM Rules for Java

}
# sets the current package used for generated class files. This rule must be
# invoked prior to invoking JarFile or Classes
rule SetPackage
{
#<[1 - end] fully qualified class name with one component per index
CURR_PACKAGE = $(<[1]) ;
PACKAGE_PATH = $(<[1]) ;

for i in $(<[2-]) {
CURR_PACKAGE = $(CURR_PACKAGE)$(SLASH)$(i) ;
PACKAGE_PATH = $(PACKAGE_PATH).$(i) ;
}

ECHO "Current package set to: "$(CURR_PACKAGE) ;


}
# add the target directory to the list of directories to add to a JAR file
rule AddPackageToJar {
JAR_DIRS += $(DESTDIR)$(<) ;
}
# Generate class files for each Java file target
rule Classes
{
#ECHO "Processing rule Classes" ;
for i in $(<[1-]) {
c = $(DESTDIR)$(CURR_PACKAGE)$(SLASH)$(i:S=.class) ;
CLASS_FILES += $(c) ;

if (USE_FULL_PATH_FOR_SOURCE = TRUE) {
j = $(c:S=.java) ;
} else {
j = $(c:B).java ;
}

#ECHO "In rule Classes on: "$(j) ;

SEARCH on $(j) = $(SEARCH_SOURCE) ;


LOCATE on $(c) = $(DESTDIR) ;

Javac $(c) : $(j) ;


}
}
# these flags used by rule Javac to allow different settings on a per file
# basis when compiling.
JC_FLAGS = ;
rule Javac
{
#ECHO In rule Javac on: $(<) and $(>) ;
DEPENDS $(<) : $(>) ;

JAM Overview C-5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
Custom JAM Rules for Java

JC_FLAGS on $(<) = $(JCFLAGS) ;

Clean clean : $(<) ;


}
actions Javac
{
echo $(JAVAC) $(JC_FLAGS) -d $(DESTDIR) $(>)
$(JAVAC) $(JCFLAGS) -d $(DESTDIR) $(>)
}
rule Rmic
{
local skel = ;
local source = ;
local fullname = ;

skel = $(DESTDIR)$(CURR_PACKAGE)$(SLASH)$(<:S=_skel.class) ;
fullname = $(PACKAGE_PATH).$(<:B) ;

if (USE_FULL_PATH_FOR_SOURCE = TRUE) {
source = $(DESTDIR)$(CURR_PACKAGE)$(SLASH)$(<:S=.java) ;
} else {
source = $(<).java ;
}

SEARCH on $(source) = $(SEARCH_SOURCE) ;


LOCATE on $(skel) = $(DESTDIR) ;

RunRmic $(skel) : $(fullname) : $(source) ;


Clean clean : $(skel) $(stub) ;
}
rule RunRmic
{
CLASS_FILES += $(<) ;
DEPENDS $(<) : $(3) ;
}
actions RunRmic
{
rmic -d $(DESTDIR) $(>:B)$(>:S)
}
# these variables used by JarFile rule to allow multiple jars to be
# generated in a single run.
DIRS = ;
MANIFEST_FILE = ;
J_OPTIONS = ;
# generate a jar file using second argument java files, all class files in the
# $(JAR_PACKAGES), $(JAR_MEMBERS).
rule JarFile
{
j = ;
for i in $(>)

C-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
C
Custom JAM Rules for Java

{
switch $(i:S)
{
case .java : j += $(i) ;
case * : JARMEMBERS += $(i) ;
}
}
if $(j) { Classes $(j) ; }
DEPENDS $(<) : $(CLASS_FILES) $(JAR_MEMBERS) $(MANIFEST) ;

DIRS on $(<) = $(JAR_DIRS) ;


MANIFEST_FILE on $(<) = $(MANIFEST) ;
J_OPTIONS on $(<) = $(JAR_OPTIONS) ;
Clean clean : $(<) ;

ECHO "Through processing for JAR file" ;


if $(JAR_MEMBERS) { Print $(JAR_MEMBERS) : " Jar members: " ; }
Print $(JAR_DIRS) : " Jar directories: " ;
ECHO " " ;
}
actions JarFile
{
$(JAR) $(J_OPTIONS) $(<) $(MANIFEST_FILE) $(DIRS) $(JAR_MEMBERS)
}
# echo the contents of the target
rule Print
{
if $(<)
{
dirs = ;
space = " " ;
msg = "Field values: " ;
if $(>) { msg = $(>) ; }
for i in $(<) {
if $(dirs) { dirs = $(dirs)$(space)$(i) ; } else { dirs = $(i) ; }
}

ECHO $(msg)$(dirs) ;
}
}

JAM Overview C-7


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Glossary

address
A location on a computer network, on a peripheral device, or in
computer memory.
address space
The range of memory locations to which a CPU can refer;
effectively, the amount of memory a CPU could use if all of the
memory were available.
applet
A Java program that can be included in an HTML page using
the applet tag.
application
Any specific use of the computer. The term is often used
synonymously with program.
application programmer’s interface (API)
The interface to a library or package of language-specific
functions or methods.
Bean
A reusable software component that can be manipulated
visually in a builder tool.
beanbox
A test container for testing your Bean components.
browser
A program used to view World Wide Web materials and
capable of interpreting URLs and understanding different
Internet protocols.

Glossary-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
class loader
A class loader is the foundation of the Java Virtual Machine
(JVM). A class loader is an executable class object that converts
a named class into the bits that make up an implementation of
that class. Class loaders enable the JVM to load a class without
having to know anything about the underlying file system
semantics. Class loaders extend the abstract class
java.lang.ClassLoader and implement the loadClass
method at minimum.
client
A software program that requests information or services from
another software application (server). For example, a browser is
a client that accesses data from HTTP servers.
Common Object Request Broker Architecture (CORBA)
The architecture and specifications aimed at software
developers and designers who want to produce applications
that comply with OMG standards for the ORB.
content handler
A specialized Java program that enhances Java functionality by
providing a means to understand a new content type; for
example, email, video, or audio files of nonsupported types. It
is responsible for reading data from a stream (provided by a
protocol handler) and returning an object representation of the
stream’s content.
component architecture model
A software model that enables developers to create software
pieces called components that can be combined together to
create applications.
distributed application
A program that makes calls to other address spaces, possibly on
another physical machine.
distributed computing
The technique of allowing applications running on one machine
to access applications that are running on another machine.
That is, client programs make calls to programs in other address
spaces, either local or remote.
distributed object computing
An extension of distributed computing, where objects are
implemented in an address space separate from the client
program.

Glossary-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
event
An event is asynchronous data generated by the window server
and which results from some device activity.
event source
An object that generates (fires) an event.
event listener
An object that registers itself with an event source, indicating it
should be notified of events fired by the event source.
externalizable
Java objects are externalizable when they implement the
java.io.Externalizable interface and implement the
methods writeExternal(ObjectOutput out) and
readExternal(ObjectInput in). Externalizable objects are
serializable, but only the identity of the class is saved by
default—it is the responsibility of the class to save and restore
the contents of the object.
firewall
A machine or machines that run filtering and logging software,
which restrict and/or monitor traffic passing from one network
to another. A firewall is the single point through which all
traffic between two networks must pass, so that network and
application security policies can be implemented.
FTP
File Transfer Protocol is an Internet client-server protocol for
transferring files between computers.
GUI
Graphical user interface.
HTTP
Hypertext Transfer Protocol. The most common protocol used
on the World Wide Web to transfer hypertext documents.
idlgen
A command used to compile JavaIDL.
Interface Definition Language (IDL)
The Object Management Group (OMG) defined a set of
language constructs that can be used to define the interface
between an implementation of the interface and an application
that executes operations on the interface. The Interface
Definition Language (IDL) is the result of their work. The IDL
defines a “contract” of services. Each service encapsulates

Glossary Glossary-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
operations and attributes and can specify exceptions that occur.
IDL is not a programmatic language—the IDL file must be
compiled to the specific language implementation desired.
Internet
The world-wide network of computers communicating using
the TCP/IP protocols.
introspection
The process provided by the JavaBeans API to enable builder
tools to discover the properties, methods, events, and behavior
of Bean components.
Java
A programming language developed by Sun Microsystems™
that enables dynamic Web pages.
JavaBeans
A portable, platform-independent component model written in
the Java language.
JDBC API
A set of interfaces designed to insulate a database application
developer from a specific database vendor.
JavaIDL API
A set of classes and interfaces that enables developers to define
a set of remote interfaces using the CORBA IDL standard and
maps IDL constructs onto a set of stubs and skeletons that can
be used to create a CORBA implementation.
multicast
A special form of broadcast where copies of the packet are
delivered to only a subset of all possible destinations.
multicast source
An event source that is allowed to have many event listeners at
the same time.
network
A group of connected computers.
NFS
A distributed application that enables remote file systems to be
accessed by the end-user in the same way as that user would
access a local file system.

Glossary-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Object Management Group (OMG)
A nonprofit international consortium dedicated to promoting
the theory and practice of object technology for the
development of distributed computing systems.
Object Request Broker (ORB)
A program that provides the communications infrastructure
that enables objects to transparently make and receive requests
and responses in a distributed environment.
Object Serialization API
A set of classes and interfaces that enables developers to write
Java code that creates persistent storage for Java objects.
one-tier database design
A database written as a single unit, with both the database
engine and the user interface tightly coupled.
protocol
An agreed convention for inter-computer communication.
protocol handler
A specialized Java program that enhances Java functionality by
providing a means to understand a new protocol type; for
example, IPX/SPX or Asynchronous Transfer Mode (ATM). It is
responsible for establishing a connection and defining data
stream syntax (how data will pass from one endpoint to
another). It will return a connection object that can then be used
for opening data streams.
RMI API
A set of classes and interfaces designed to enable developers to
make calls to remote objects that exist in the runtime of a
different virtual machine invocation.
reflection
A low-level process defined by the Reflection API that uses
naming conventions for properties, methods, and events to
discover the behavior of Bean components.
Remote Procedure Call (RPC)
A paradigm for implementing the client-server model of
distributed computing. A request is sent to a remote system to
execute a designated procedure, using arguments supplied, and
the result is returned to the caller.

Glossary Glossary-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
replicated
An object that has one or more exact copies of itself available
from multiple address spaces. For example, under NIS+,
Replica Servers provide the same information to clients as the
Master Server, and it is irrelevant to the client as to which server
the information comes from.
rmic
The RMI compiler that generates the RMI sub and skeleton
classes.
rmiregistry
An application that provides a simple naming lookup service of
remote objects in the RMI API.
Security Manager API
A class that enables developers to set and control the security
policy that must be followed by Java programs running on a
system.
serializable
Java objects are serializable if they implement the
java.io.Serializable interface and meet the following
criteria: they do not contain references to nonserializable objects
(for example, java.lang.Thread,
java.io.FileOutputStream) unless these references are
marked with the transient keyword. An object that is
serializable may be serialized.
serializing or serialized
Java objects that are serializable can be sent as a stream of bytes
over any type of java.io.Output stream and retrieved using
any type of java.io.InputStream. This includes files, pipes,
and sockets. An object is said to be serialized when it is
converted from its internal in-memory format to the stream of
bytes that can be sent over the wire.
server
In the client-server model for file systems, the server is a
machine with compute resources (and is sometimes called the
compute server) and large memory capacity.
skeleton
A server-side entity that contains a method that dispatches calls
to the actual remote object implementation.

Glossary-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
socket
A software endpoint for network communication. Two
programs on different machines each open a socket in order to
communicate over the network. This is the low-level
mechanism that supports most networking programs.
stub
A proxy for a remote object that is responsible for forwarding
method invocations on remote objects to the server where the
actual remote object implementation resides.
TCP
Transport Control Protocol. A virtual circuit protocol of the
Internet protocol family. It provides reliable, flow-controlled, in
order, two-way transmission of data in a byte stream.
transitional Beans
Bean components that are fully compliant with the JavaBeans
1.0 architecture, but which run on JDK 1.0.2 applications, such
as browsers.
thread
In programming, a process that is part of a larger process or
program.
three-tier database design
A database design that introduces an intermediary tier between
the database front end and the database engine. This
intermediary tier can support functionality such as mirroring,
secure transactions, and caching.
two-tier database design
A database design that separates the database front end from
the database engine, enabling the data to reside locally or
remotely.
UDP
User Data Protocol. A transport protocol in the Internet suite of
protocols using datagrams.
unicast source
An event source that can have only one event listener defined at
any give time.

Glossary Glossary-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Index

Symbols B
"write once, run Bean
everywhere" 11-4 examples of 1-7
features of 1-6
A Bean storage, goals 6-5
BeanBox
ActionEvent 3-8 adding your Beans to ToolBox
ActionListener 3-9 window 2-33
actionPerformed() 3-9 BeanBox window 2-7
ActiveX bound properties 2-22
a component model 1-20 changing Bean
advantages of 1-20 properties 2-16
ActiveX bridge 11-9 connecting Beans 2-26
addActionListener() 3-9 customizers 2-19
adding your Beans to the design mode 2-9
ToolBox window 2-33 JDBC SELECT Bean 9-14
addXXXListener(XXXListener moving a Bean 2-12
l) 3-19 placing a Bean on 2-10
advantages of ActiveX 1-20 PropertySheet window 2-8
agents 9-8 QuoteMonitor Bean 9-18
APPLET tag 10-20 resizing a Bean 2-13
applets run.sh 2-5
issues as Beans 10-17 running the BeanBox 2-5
architecture overview saving and restoring 2-31
JDBC 9-12 selecting a Bean in 2-11
architetecture overview ToolBox window 2-7
RMI 9-19 what is it? 2-4
automatic analysis windows of 2-6
definition 5-14 BeanInfo file
AWT components as customizers 7-44
sources 3-18 Beans
and scripting 10-16
issues for applets 10-17

Index-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
putting Beans together 1-14 defining 4-21
Beans in distributed definition 4-5
environments 9-10 fireVetoableChange 4-24
Beans.instantiate method 5-26, overview 4-20
10-16 recap 4-30
Beans.instantiate() method 6-18 validating a property
bound property 4-14 change 4-28
defining 4-13 VetoableChangeListener 4-24
definition 4-4 VetoableChangeSupport 4-24
firePropertyChange 4-14 constructors
overview 2-22 for customizers 7-45
recap 4-19 constructors for property
building Beans sheets 7-16
composing a Bean from other converting 1.0 event handling to
Beans 10-10 1.1 A-3
from a serialized CORBA 9-32
prototype 10-11, 10-12 creating applets and applications
from scratch 10-4 with Beans 10-14
inheriting from a Bean 10-5 creating transitional Beans 12-6
options for 10-4 creating your own source 3-18
subclassing a Bean and customer class for a Bean 2-19
adding BeanInfo 10-6 customization
definition 7-4
C customizers
BeanInfo file 7-44
capitalize rules 5-24 characteristics of 7-42
category of events 3-10 extending Component 7-45
changing Bean properties 2-16 implementation
Class class definition 10-39 requirements 7-43
class loader definition 10-41 implementing
classes that are serialized 6-7 Customizer 7-45
ClassLoader class 10-41 naming conventions 7-42
code integration problem 5-4 null argument
common uses of adapters 8-9 constructor 7-45
component model PropertyChangeListener
ActiveX 1-18 support 7-46
major elements 11-6 setObject() method 7-47
services 11-7 when a property editor is not
services of 1-12 enough 7-7
component-based software 11-5 when to use 7-41
components 1-4
composing a Bean from other
Beans 10-10 D
connecting Beans in the DataInput interface 6-11
BeanBox 2-26 DataOutput interface 6-11
constrained property defining bound properties 4-13

Index-2 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
defining constrained method 6-18
properties 4-21 readObject method 6-14
defining simple properties 4-8 design mode of the BeanBox 2-9
definitions details of event 3-12
agents 9-8 developer rules for transitional
automatic analysis 5-14 Beans 12-8
BeanBox 2-4 diagram overview of digital
bound property 4-4 signatures 10-29
Class class 10-39 digital signatures
class loader 10-41 diagram overview 10-29
components 1-4 security and
constrained property 4-5 cryptography 10-31
customization 7-4 tools used in creating 10-33
demultiplexing adapter 8-8 display styles in property
deserialization 6-14 editors 7-23
event 3-4 distributed computing
event adapter 8-4 Java technologies 9-10
indexed property 4-5
introspection 5-9 E
JAR files 2-33
JavaBeans 1-4 Enterprise JavaBeans 9-6
JDBC 9-11 event adapters
listeners 3-6 common uses 8-9
marker classes 12-6 definition 8-4
multicast source 3-20 demultiplexing example 8-16
multiplexing adapter 8-8 differentiating from normal
naming conventions 5-8 listeners 8-12
object serialization 6-4 hookup classes 8-5
property 4-4 multiplexing lab
property sheets 7-8 overview 8-20
reflection 5-8 overview diagram 8-4
RMI 9-17 event conversion table A-4
simple property 4-4 event handling
source 3-6 before JDK 1.1 A-2
transitional Bean 12-4 converting 1.0 to 1.1 A-3
unicast source 3-21 delegation model 3-6
visual application in Beans 3-26
builders 11-14 in JDK 1.1 A-2
delegation model 3-6 listeners A-6
delivering your beans 10-18 simple code example 3-8
demultiplexing adapter event sources
example 8-16 multicast 5-20
demultiplexing adapters 8-8 unicast 5-22
deserialization 6-14 EventListener 3-17
deserializing Beans EventObject 3-13
Beans.instantiate events

Index Index-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
categories of 3-10 and security 5-54
definition of 3-4 definition 5-9
delivery issues 3-23 key concepts 5-12
obtaining details 3-12 key issued addressed 5-6, 5-7
propagatiing notification 3-7 process overview 5-11
events in the BeanBox 2-26 summary 5-55
example code Introspector.getBeanInfo
Beans in an applet 10-43 method 5-29, 5-30, 5-31
Beans in an application 10-46 issues for applets as Beans 10-17
executeQuery() method 9-12
J
F J/Crypto 10-32
firePropertyChange for a bound JAR files
property 4-14 creating 2-36
fireVetoableChange 4-24 format 2-33
in HTML 10-20
G review 10-19
security and
getConnection() method 9-12 cryptography 10-31
using in HTML files 2-35
H Java Cryptography Architecture
hooking beans together in (JCA) 10-31
applets or applications 10-50 Java Studio 11-15
hookup class 8-5 Java technologies 9-10
Java Workshop 11-15
JavaBeans
I and introspection 5-5
identifying sources 3-19 as a component model 1-4
implementing Customizer bridging to other models 11-8
interface 7-45 browser support for 12-5
indexed property design goals 1-8
definition 4-5 motivating scenarios 9-4
InfoBus technology 11-11 vision 5-5
instantiating a Bean what is it? 1-4
coding possibilities 10-36 JavaIDL
in an applet 10-37 overview 9-32
in an application 10-37 javakey 10-33
steps involved 10-35 JavaSoft distributed
integrated development technologies 9-10
environment (IDE) 11-12 JBuilder 11-17
interfaces 3-16 JDBC
creating your own listener architecture overview 9-12
interface 3-17 Connection 9-12
introspection JDBC SELECT Bean 9-14
additional information 5-53 overview 9-11

Index-4 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
ResultSet 9-12 properties
SQL statements 9-12 boolean 5-17
Statement 9-12 bound 2-22
changing 2-16
L indexed 5-18
simple 5-16
listeners properties and methods 4-6
creating your own listener properties and the BeanBox 4-31
interface 3-17 property
definition of 3-6 definition 4-4
interfaces 3-16 read-only 4-6
read-write 4-6
M types of 4-4
making a property editor write-only 4-6
known 7-31 property editors
marker classes display styles 7-23
definition of 12-6 how an editor is found 7-31
Mojo 11-16 naming conventions 7-32
moving a Bean 2-12 null argument
multicast source 3-20 constructor 7-16
multiplexing adapter 8-8 PropertyChangeListener
multiplexing adapter lab support 7-18
overview 8-20 PropertyEditor interface 7-15
PropertyEditorSupport
class 7-29
N setValue() method 7-17
naming conventions supporting new property
customizers 7-42 types 7-6
definition 5-8 property sheets
events 5-20 definition 7-8
methods 5-24, 5-25 PropertySheet window of
properties 5-15 BeanBox 7-5
property editors 7-32 PropertyCanvas view 4-33
PropertyChangeListener
support
O customizers 7-46
object serialization, PropertyChangeListener
definition 6-4 support in property
ObjectInput interface 6-11 editors 7-18
ObjectInputStream class 6-14 PropertyChangeSupport
ObjectOutputStream class 6-12 class 4-14
PropertyDescriptor class 5-37
P PropertyEditor interface 7-15
PropertyEditorSupport
placing a Bean onto the
class 7-29
BeanBox 2-10
PropertySelector view 4-34

Index Index-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
PropertySheet window 2-8 serializable
properties on 4-32 Beans.instantiate() 6-18
views 4-33 classes 6-7
PropertyText view 4-34 event adaptors 6-8
putting Beans together 1-14 fields automatically
serialized 6-9
Q fields not serialized 6-9
ObjectInput interface 6-11
QuoteMonitor Bean 9-18 ObjectInputStream class 6-14
ObjectOutputStream 6-12
R references to external
rapid application development Beans 6-8
(RAD) 11-13 static 6-9
readObject() method 6-14 the interface 6-6
reflection transient 6-9
advantages 5-50 what is not saved 6-8
and JavaBeans 5-50 what is saved 6-8
definition 5-8 writeObject method 6-12
major classes in the API 5-52 serializing Beans 6-12
remote reference layer 9-20 services of component
removeXXXListener(XXXListene models 1-12
r l) 3-19 setObject() method 7-47
resizing a Bean 2-13 setValue() method 7-17
RMI simple property
architecture overview 9-19 defining 4-8
definition 9-17 definition 4-4
exercise code conceptual sources
overview 9-22 creating your own 3-18
exercise code source files 9-23 definition of 3-6
QuoteMonitor Bean 9-18 identifying 3-19
remote reference layer 9-20 multicast 3-20
rmic commant 9-21 notifying your listeners 3-22
rmiregistry 9-21 provided by the AWT
stubs and skeletons 9-21 package 3-18
transport layer 9-20 unicast 3-21
rmic command 9-21 SQL statements 9-12
rmiregistry application 9-21 stub and skeleton layer 9-21
run.sh 2-5 subclassing a Bean and adding
BeanInfo 10-6

S
T
saving and restoring the
ToolBox window 2-7
BeanBox 2-31
TooManyListenersException 3-2
scripting and Beans 10-16
1
security and cryptography 10-31
transient keyword 6-10
selecting a Bean 2-11

Index-6 JavaBeans Component Development


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
transitional Beans
compatibility with JavaBeans
FCS 12-4
creating 12-6
definition 12-4
developer rules 12-8
example 12-10
transport layer 9-20

U
unicast source 3-21
using a builder tool 10-15

V
validating a property
change 4-28
VetoableChangeListener 4-24
VetoableChangeSupport
class 4-24
views
determining 4-35
examples of 4-36
PropertyCanvas 4-33
PropertySelector 4-34
PropertyText 4-34
visual application builders
definition 11-14
Java Studio 11-15
Java Workshop 11-15
JBuilder 11-17
Mojo 11-16
Visual Café 11-16
VisualAge 11-17
Visual Café 11-16
VisualAge 11-17

W
windows of the BeanBox 2-6
writeObject() method 6-12

Index Index-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
Index-8 JavaBeans Component Development
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1998, Revision A.4
BeCopyright 1998 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, Californie 94303, U.S.A. Tous droits réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou documentat associée ne peut être reproduite
sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de
licence, s’il y en a.
Des parties de ce produit pourront être dérivées du système Berkeley BSD licenciés par l’Université de Californie. UNIX
est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company Ltd. Le
logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un
copyright et licencié par des fournisseurs de Sun.
Sun, Sun Microsystems, le logo Sun, sont des marques fabrique ou des marques déposées de Sun Microsystems, Inc. aux
Etats-Unis et dans d’autres pays. Toutes les marques SPARC, utilisées sous licence, et sont des marques de fabrique ou des
marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres pays. Les produits portant les marques
SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
L’ interface d’utilisation graphique OPEN LOOK® et Sun™ a été développée par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant aussi les licenciés de Sun qui mettent en
place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
Le système X Window est un produit de X Consortium, Inc.
CETTE PUBLICATION EST FOURNIE “EN L’ETAT” ET AUCUNE GARANTIE, EXPRESSE OU IMPLICITE, N’EST
ACCORDEE, Y COMPRIS DES GARANTIES CONCERNANT LA VALEUR MARCHANDE, L’APTITUDE DE LA
PUBLICATION A REPONDRE A UNE UTILISATION PARTICULIERE, OU LE FAIT QU’ELLE NE SOIT PAS
CONTREFAISANTE DE PRODUIT DE TIERS. CE DENI DE GARANTIE NE S’APPLIQUERAIT PAS, DANS LA MESURE
OU IL SERAIT TENU JURIDIQUEMENT NUL ET NON AVENU.

Please
Recycle

You might also like