bean intro
TRANSCRIPT
Java BeansJava Beans
ContentContent
What is a Java Bean?What is a Java Bean? BDKBDK What makes Bean possible?What makes Bean possible? Support for Java BeanSupport for Java Bean ReferencesReferences
What are Java Beans?What are Java Beans?
Software ComponentSoftware Component Specified interfaces.Specified interfaces. Independent deployment.Independent deployment.
Analogy Analogy Electronic components.Electronic components. Automotive components.Automotive components.
What are Java Beans? ...What are Java Beans? ...
Definition:Definition:
““A Java bean is a reusable software component that A Java bean is a reusable software component that can be visually manipulated in builder tools.” can be visually manipulated in builder tools.”
Java Bean TutorialsJava Bean Tutorials
The JavaBeans Specs are available for d/l The JavaBeans Specs are available for d/l atathttp://http://java.sun.com/products/javabeans/docsjava.sun.com/products/javabeans/docs//
What is JavaBeans?What is JavaBeans? A Java Bean is a reusable software A Java Bean is a reusable software
component that can be manipulated component that can be manipulated visually in a builder toolvisually in a builder tool JavaBeans is a JavaBeans is a portable, platform-independent component portable, platform-independent component
modelmodel written in the Java programming language, written in the Java programming language, developed in collaboration with industry leaders. developed in collaboration with industry leaders.
It enables developers to It enables developers to writewrite reusable components reusable components onceonce and and runrun them them anywhereanywhere -- benefiting from the platform- -- benefiting from the platform-independent power of Java technology.independent power of Java technology.
The goal of JavaBeans is to create a system whereby The goal of JavaBeans is to create a system whereby application developers can take a set of beans from a application developers can take a set of beans from a stock library and wire them together to make a full stock library and wire them together to make a full applicationapplication
Software ComponentsSoftware Components
“A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can be deployed independently and is subject to composition by third parties.”
Szyperski ECOOP96
Composition not InheritanceComposition not InheritanceIn OO languages, new objects are created from old using the inheritance mechanism.
Pluggable components are connected together by composition rather than inheritance.
Most of the flexibility of inheritance can be gained from various compositional tactics.
Features of JavaBeansFeatures of JavaBeans Support for Support for introspectionintrospection
so that a builder tool can analyze how a bean worksso that a builder tool can analyze how a bean works Support for Support for customizationcustomization
so that when using an application builder a user can so that when using an application builder a user can customize the appearance and behavior of a beancustomize the appearance and behavior of a bean
Support for Support for eventsevents as a simple communication metaphor than can be used as a simple communication metaphor than can be used
to connect up beansto connect up beans Support for Support for propertiesproperties
both for customization and for programmatic useboth for customization and for programmatic use Support for Support for persistencepersistence
so that a bean can be customized in an application so that a bean can be customized in an application builder and then have its customized state saved away builder and then have its customized state saved away and reloaded laterand reloaded later
Persistent StoragePersistent Storage
Purpose:Purpose: To use existing data formats and plug into OLE or To use existing data formats and plug into OLE or
OpenDoc documents (e.g., Excel doc inside a Word doc)OpenDoc documents (e.g., Excel doc inside a Word doc) To be “trivial” for the common case of a tiny Bean (by To be “trivial” for the common case of a tiny Bean (by
saving its internal state)saving its internal state) SolutionsSolutions
ExternalizationExternalization: provides a Bean with full control over : provides a Bean with full control over the resulting data layout.the resulting data layout.
SerializationSerialization: provides an automatic way of storing out : provides an automatic way of storing out and restoring the internal state of a collection of Java and restoring the internal state of a collection of Java objectsobjects
All bean must support either Serialization or ExternalizationAll bean must support either Serialization or Externalization
Software ComponentsSoftware Components
ButtonsButtons Text FieldsText Fields List BoxesList Boxes Scroll BarsScroll Bars DialogsDialogs VBX, OLEVBX, OLE
Visually Manipulated, Builder Visually Manipulated, Builder ToolsTools
Property Sheet
Method Tracer
BeanBoxToolBox
BDK...BDK...
Selecting the eventsSelecting the events
Attaching EventsAttaching Events
Generating Adapter...Generating Adapter...
Making an Applet is a click Making an Applet is a click away!away!
Applet Done!Applet Done!
What makes this possible?What makes this possible?
PropertiesProperties EventsEvents PersistencePersistence IntrospectionIntrospection CustomizationCustomization
PropertiesProperties
Attributes.Attributes. Can be read/write, read-only or write-Can be read/write, read-only or write-
only.only. Several types of properties:Several types of properties:
SimpleSimple IndexedIndexed BoundBound ConstrainedConstrained
Design Pattern rulesDesign Pattern rulesConstructors A bean has a no argument constructor
Simple Properties public T getN()public void setN ( T value)
Boolean Properties public boolean isN()public boolean getN()public void setN(boolean value)
Indexed Properties public T getN(int index)public T[] getN()public void setN(int index, T value)public void setN(T[] values)
Coding examples for Coding examples for PropertiesProperties
public class alden2 extends Canvas {public class alden2 extends Canvas {
String ourString = “Hello”;String ourString = “Hello”;
public alden2() {public alden2() {
setBackground (Color.red);setBackground (Color.red);
setForeground (Color.blue);setForeground (Color.blue);
}}
public void setString (String newString) { ourString = newString; }public void setString (String newString) { ourString = newString; }
public String getString() { return ourString; }public String getString() { return ourString; }
public Dimension getMinimunSize() {public Dimension getMinimunSize() {
return new Dimension (50, 50);return new Dimension (50, 50);
}}
}}
Bound PropertiesBound Properties
Generates notification when a property is Generates notification when a property is changed.changed.
public class propertDemo extends Canvas {public class propertDemo extends Canvas {
String ourString = “Hello”;String ourString = “Hello”;
private PropertyChangeSupport changes = new PropertyChangeSupport(this);private PropertyChangeSupport changes = new PropertyChangeSupport(this);
......
public void setString (String newString) {public void setString (String newString) {
String oldString = ourString;String oldString = ourString;
ourString = newString;ourString = newString;
changes.firePropertyChange(“string”, oldString, newString);changes.firePropertyChange(“string”, oldString, newString);
}}
......
Bound Properties...Bound Properties...
......
public void addPropertyChangeListener (PropertyChangeListener l) public void addPropertyChangeListener (PropertyChangeListener l) {{
changes.addPropertyChangeListener (l);changes.addPropertyChangeListener (l);
}}
public void removePropertyChangeListener public void removePropertyChangeListener (PropertyChangeListener l) {(PropertyChangeListener l) {
changes.removePropertyChangeListener(l);changes.removePropertyChangeListener(l);
}}
}}
Constrained PropertyConstrained Property
The concept of a Watcher object.The concept of a Watcher object. subscribe to the ‘VetoableChange’subscribe to the ‘VetoableChange’
Can veto a property change using a Can veto a property change using a PropertyVetoException.PropertyVetoException.
Constrained Property...Constrained Property...
public class JellyBean extends Canvas {public class JellyBean extends Canvas {
private PropertyChangeSupport changes = new private PropertyChangeSupport changes = new PropertyChangeSupport (this);PropertyChangeSupport (this);
private VetoableChangeSupport vetos = new private VetoableChangeSupport vetos = new VetoableChangeSupport (this);VetoableChangeSupport (this);
......
public void setColor (int newColor) throws public void setColor (int newColor) throws PropertyVetoException {PropertyVetoException {
int oldColor = currentColor;int oldColor = currentColor;
vetos.fireVetoableChange(“setColor”, vetos.fireVetoableChange(“setColor”, newInteger(oldColor),newInteger(oldColor),
newInteger(newColor));newInteger(newColor));
currentColor = newColor;currentColor = newColor;
Constrained Property...Constrained Property...
changes.firePropertyChange(“setColor”, new Integer(oldColor),changes.firePropertyChange(“setColor”, new Integer(oldColor),
new Integer(newColor));new Integer(newColor));
}}
public void addVetoableChangeListener (VetoableChangeListener l) {public void addVetoableChangeListener (VetoableChangeListener l) {
vetos.addVetoableChangeListener(l);vetos.addVetoableChangeListener(l);
}}
public void removeVetoableChangeListener(VetoableChangeListener l) public void removeVetoableChangeListener(VetoableChangeListener l) {{
vetos.removeVetoableChangeListener(l);vetos.removeVetoableChangeListener(l);
}}
}}
EventsEvents
Two types of objects are involved:Two types of objects are involved: ““Source” objects.Source” objects. ““Listener” objects.Listener” objects.
Based on registration.Based on registration. Makes use of parametric Makes use of parametric
polymorphism.polymorphism.
EventsEvents Message sent from one object to another.Message sent from one object to another. Sender Sender firesfires event, recipient (listener) event, recipient (listener)
handleshandles the event the event There may be many listeners.There may be many listeners.
Eventsource
Eventlistener
Fire eventEvent Object
Register listener
Eventsource
EventAdapter
Fire eventEvent Object
Register event listener
EventListener
Forward eventEvent Object Provide
interface
Bean EventsBean Events•Define a new Event class which extends EventObject. XEvent
•Define a new interface for listeners to implement, this must be an extension of EventListener. XEventListener
•The Source must provide methods to allow listeners to register and unregister eg addXListener(), removeXListener().
•The source must provide code to generate the event and send it to all registered listeners. fireXEvent()
•The listener must implement the interface to receive the event.changeX()
•The listener must register with the source to receive the event.
EventsEvents
public class eventSource extends GenericEventGenerator {public class eventSource extends GenericEventGenerator {
......
private Vector myListeners = new Vector();private Vector myListeners = new Vector();
......
public synchronized void addMyEventListeners ( MyEventListener public synchronized void addMyEventListeners ( MyEventListener l) {l) {
myListeners.addElement(l);myListeners.addElement(l);
}}
public synchronized void removeMyEventListeners public synchronized void removeMyEventListeners ( MyEventListener l) {( MyEventListener l) {
myListeners.removeElement(l);myListeners.removeElement(l);
}}
......
Events...Events...
private void fanoutEvents() {private void fanoutEvents() {
Vector l;Vector l;
synchronized (this) {synchronized (this) {
l = (Vector) myListener.clone();l = (Vector) myListener.clone();
}}
for (int i = 0; i < l.size(); i++) {for (int i = 0; i < l.size(); i++) {
MyEventListener mel = (MyEventListener) l.elementAt(i);MyEventListener mel = (MyEventListener) l.elementAt(i);
mel.handleThisEvent (this);mel.handleThisEvent (this);
}}
}}
PersistencePersistence
Allows the graphical builder to recall Allows the graphical builder to recall the state of a bean.the state of a bean.
public class Button implements java.io.Serializable { ... }public class Button implements java.io.Serializable { ... }
Selected property fields can bypass Selected property fields can bypass the serialization using keywords the serialization using keywords transienttransient or or staticstatic..
Persistence...Persistence...
writeObject and readObjectwriteObject and readObjectprivate void writeObject (java.io.ObjectOutputStream s) private void writeObject (java.io.ObjectOutputStream s)
throws java.io.IOException{}throws java.io.IOException{}
private void readObject (java.io.ObjectInputStream s) private void readObject (java.io.ObjectInputStream s)
throws java.io.IOException, throws java.io.IOException, java.lang.ClassNotFoundException {}java.lang.ClassNotFoundException {}
Allows the customization of objects.Allows the customization of objects. Appearance and behavior can be stored Appearance and behavior can be stored
and recalled.and recalled. Don’t store references to other beans.Don’t store references to other beans.
IntrospectionIntrospection
A mechanism that allows the builder A mechanism that allows the builder tool to analyze a bean.tool to analyze a bean.
Two ways to analyze a bean:Two ways to analyze a bean: low-level reflection APIs.low-level reflection APIs. vendor provided explicit information vendor provided explicit information
(Customization).(Customization). Application builder will provide default Application builder will provide default
BeanInfo class BeanInfo class <classname>BeanInfo.<classname>BeanInfo.
BDK ExampleBDK Examplepackage acme.beans;package acme.beans;
import java.awt.*;import java.awt.*;
import java.io.Serializable;import java.io.Serializable;
public class Acme04Bean extends Canvas implements Serializable {public class Acme04Bean extends Canvas implements Serializable {
public Acme04Bean() {public Acme04Bean() {
resize(60,40);resize(60,40);
this.label="Bean";this.label="Bean";
setFont(new Font("Dialog", Font.PLAIN, 12));setFont(new Font("Dialog", Font.PLAIN, 12));
}}
Introspection...Introspection...public void paint(Graphics g) {public void paint(Graphics g) {
g.setColor(beanColor);g.setColor(beanColor);
g.setColor(Color.blue);g.setColor(Color.blue);
int width = size().width;int width = size().width;
int height = size().height;int height = size().height;
FontMetrics fm = g.getFontMetrics();FontMetrics fm = g.getFontMetrics();
g.drawString(label, (width - fm.stringWidth(label)) / 2, g.drawString(label, (width - fm.stringWidth(label)) / 2,
(height + fm.getMaxAscent() - fm.getMaxDescent()) / 2);(height + fm.getMaxAscent() - fm.getMaxDescent()) / 2);
}}
public Color getColor() {public Color getColor() {
return beanColor;return beanColor;
}}
Introspection...Introspection... public void setColor(Color newColor) {public void setColor(Color newColor) {
beanColor = newColor;beanColor = newColor;
repaint();repaint();
}}
public String getLabel() {public String getLabel() {
return label;return label;
}}
public void setLabel(String newLabel) {public void setLabel(String newLabel) {
String oldLabel = label;String oldLabel = label;
label = newLabel;label = newLabel;
}}
private Color beanColor = Color.cyan;private Color beanColor = Color.cyan;
private String label;private String label;
}}
Introspection...Introspection...
CustomizationCustomization
Similar to Introspection.Similar to Introspection. Develop your own Develop your own
<classname>BeanInfo<classname>BeanInfo class which class which extends extends SimpleBeanInfoSimpleBeanInfo..
Develop your own Develop your own <classname>Editor<classname>Editor class which class which extends extends PropertyEditorSupportPropertyEditorSupport to to custom build your property editor.custom build your property editor.
Customization ...Customization ...<classname>BeanInfo<classname>BeanInfo
package sun.beanbox.beans;package sun.beanbox.beans;
import java.beans.*;import java.beans.*;
public class NervousText07BeanInfo extends SimpleBeanInfo {public class NervousText07BeanInfo extends SimpleBeanInfo {
private final static Class beanClass =private final static Class beanClass =
NervousText07.class;NervousText07.class;
public BeanDescriptor getBeanDescriptor() {public BeanDescriptor getBeanDescriptor() {
BeanDescriptor bd = new BeanDescriptor(beanClass);BeanDescriptor bd = new BeanDescriptor(beanClass);
bd.setDisplayName("Uneasy Text 07");bd.setDisplayName("Uneasy Text 07");
return bd;return bd;
}}
Customization...Customization...
public PropertyDescriptor[] getPropertyDescriptors() {public PropertyDescriptor[] getPropertyDescriptors() {
try {try {
PropertyDescriptor textPD =PropertyDescriptor textPD =
new PropertyDescriptor("text", beanClass);new PropertyDescriptor("text", beanClass);
PropertyDescriptor rv[] = {textPD};PropertyDescriptor rv[] = {textPD};
textPD.setPropertyEditorClass(NervousText07TextPropertyEditor.class);textPD.setPropertyEditorClass(NervousText07TextPropertyEditor.class);
return rv;return rv;
} catch (IntrospectionException e) {} catch (IntrospectionException e) {
throw new Error(e.toString());throw new Error(e.toString());
}}
}}
}}
Customization...Customization...<classname>Editor<classname>Editor
package sun.beanbox.beans;package sun.beanbox.beans;
import java.beans.*;import java.beans.*;
public class public class NervousText07TextPropertyEditorNervousText07TextPropertyEditor
extends PropertyEditorSupport {extends PropertyEditorSupport {
public String[] getTags() {public String[] getTags() {
String values[] = {String values[] = {
"Nervous Text","Nervous Text",
"Anxious Text","Anxious Text",
"Funny Text","Funny Text",
"Wobbly Text"};"Wobbly Text"};
return values;return values;
}}
}}
BDK OutputBDK Output
ConclusionConclusion
Easy to use.Easy to use. Difficult to build.Difficult to build. Like all OO design, needs careful Like all OO design, needs careful
planning.planning. Similar to the String library in C++.Similar to the String library in C++. Wide selection of JavaBeans in the Wide selection of JavaBeans in the
future?future?
SupportSupport
BDK - BDK - SunSun NetBeans – www.netbeans.orgNetBeans – www.netbeans.org Jbuilder - Jbuilder - InpriseInprise Super Mojo - Super Mojo - Penumbra SoftwarePenumbra Software Visual Age for Java - Visual Age for Java - IBMIBM Visual Cafe - Visual Cafe - Symantec CorporationSymantec Corporation JDeveloper Suite - JDeveloper Suite - OracleOracle
ReferencesReferences
http://java.sun.com/products/http://java.sun.com/products/javabeans/javabeans/
Java Developer Connection TutorialsJava Developer Connection Tutorials Java Beans, Part 1 to 4Java Beans, Part 1 to 4 http://developer.java.sun.com/http://developer.java.sun.com/
developer/onlineTraining/developer/onlineTraining/
References...References...
Trail: JavaBeansTrail: JavaBeans http://java.sun.com/docs/books/tutorial/http://java.sun.com/docs/books/tutorial/
javabeans/index.htmljavabeans/index.html JavaBeans 1.01 SpecificationJavaBeans 1.01 Specification
http://java.sun.com/beans/docs/http://java.sun.com/beans/docs/spec.htmlspec.html