Transcript PPT
ICS 123
JavaBeans*
ICS 123
Richard N. Taylor & Eric M. Dashofy
UC Irvine
http://www.isr.uci.edu/classes/ics123s02/
*with the usual thanks to David Rosenblum
Topic 12
JavaBeans
What Is JavaBeans?
ICS 123
• (One of) Sun Microsystems’s entry in the component sweepstakes
– Currently realized in Beans Development Kit (BDK) 1.1 spec (1999)
• Component model for Java
– Platform-independent
– Language-dependent
• Implemented as language extensions
– Additional classes and interfaces in the Java Class Library
• Basically a design pattern
Based on standard naming conventions
– The naming conventions allow beanboxes and other beans to dynamically discover a
bean’s capabilities
– But naming conventions have well-known problems
• Detailed documentation is available at
http://java.sun.com/products/javabeans/
2
Topic 12
JavaBeans
Three Levels of Use
ICS 123
Building applications from beans written by bean
developers
Developing individual beans
Developing “beanboxes” and other tools for
graphically manipulating beans
– A more neutral term for such tools is “sandboxes”
3
Topic 12
JavaBeans
What Is a Bean?
ICS 123
• A bean is a Java object
Exports properties, events and methods
Interface conforms to certain naming rules
Conforms to certain packaging rules
Usually (but not always) has a visual form for manipulation in
beanboxes
– Supported by package java.beans
–
–
–
–
• Any Java class can be a bean
– No predefined Bean class
• Many AWT components are beans
4
Topic 12
JavaBeans
A Bare-Bones Bean
ICS 123
public class Airplane extends Canvas {
public Airplane() {
setBackground(Color.white);
// Plus other visual settings and
setForeground(Color.blue);
//
other initialization
}
public Dimension getPreferredSize() {
return new Dimension(50,50); // Or whatever is appropriate
}
public Dimension getMinimumSize() {
return getPreferredSize(); // Or return an actual Dimension
}
}
• Canvas is subclassed to make the bean a GUI object having
its own window
• Can subclass Component instead to create a “lightweight
component” without its own window
5
Topic 12
JavaBeans
Elements of JavaBeans (I)
ICS 123
• Events signal a bean’s response to changes in its
properties and other phenomena
• Properties represent attributes of a bean
• BeanInfo customizes the information about a bean
that is made available within a beanbox
6
Topic 12
JavaBeans
Elements of JavaBeans (II)
ICS 123
• Customizers allow customization of a bean’s
appearance and behavior in beanboxes
• PropertyEditors define custom editors for a specific
property
• JAR files are archive files containing all the artifacts
related to a bean
– Manifest files describe the content of JAR files
7
Topic 12
JavaBeans
Events
ICS 123
• Java events are used heavily in JavaBeans
• An event in Java is an object
– Events are instances of (subclasses of) java.util.EventObject
• An event is sent by an object to a specific object
– The identity of the sender is associated with the event
• An event is sent as an argument in a method call
• An object that generates events must keep track of its own
listeners
8
So What’s So Special About
Java Events?
Topic 12
JavaBeans
ICS 123
• How do they differ from regular method calls?
– They define a protocol for asynchronous interaction
– They are generated by many predefined Java components
– They are the primary mechanism for wiring interoperation paths
between beans
• But there’s still something missing ...
9
Review:
Implicit Invocation
Topic 12
JavaBeans
ICS 123
• Advantages
Allows for decoupling and autonomy of components
Java events require tight coupling
– Enhances reuse and evolution
» Easy to introduce new components without affecting existing ones
• Disadvantages
– Components announcing events have no guarantee of getting a
response
– Components announcing events have no control over the order of
responses
– Event abstraction does not cleanly lend itself to data exchange
– Difficult to reason about the behavior of an announcing component
independently of the components that register for its events
10
Topic 12
JavaBeans
Listeners and Adapters
ICS 123
• Listeners are interfaces
– They define methods that an object must implement in order to
receive event notifications
– Listeners add and remove themselves (i.e., register and unregister)
with the source of events they’re interested in
– Event sources must provide methods to add and remove listeners
• Adapters are classes
– They are bare-bones implementations of listener interfaces
– They provide a convenient way of quickly creating event listeners
– They are usually subclassed to override a single listener method of
interest
11
Topic 12
JavaBeans
Predefined Events in Java
ICS 123
• ActionEvent: high-level user event
• AdjustmentEvent: event from an Adjustable object
(such as a scrollbar)
• ComponentEvent: event from a GUI Component
object
– Container, Focus, Input (Key or Mouse), Paint, Window
• ItemEvent: event from an ItemSelectable object
• TextEvent: event from the editing of a
TextComponent
• Many of these have associated Adapters and/or
Listeners
12
Event Handling Scenario
(involving ActionEvents)
ActionEvent Listener
ActionEventSource
Topic 12
JavaBeans
ICS 123
ActionEvent Listener
addActionListener()
actionPerformed(ae)
addActionListener()
actionPerformed(ae)
actionPerformed(ae)
removeActionListener()
actionPerformed(ae)
13
Action Event
Programming Example
Topic 12
JavaBeans
ICS 123
public class Button extends Component { // defined in java.awt
public synchronized void addActionListener(ActionListener l) {
...
}
}
protected void processEvent(ActionEvent ae) { // called internally
...
l.ActionPerformed(ae);
}
public class ButtonListener implements ActionListener {
Button button;
public ButtonListener() {
button = new Button("Press Me");
button.addActionListener(this);
}
}
14
public void ActionPerformed(ActionEvent buttonClick) {
...
}
Topic 12
JavaBeans
Properties
ICS 123
• A property of a bean is a public attribute, accessed
via Get and Set methods
– Read-only properties have only a Get method
– Write-only properties have only a Set method
– Read/Write properties have both
15
Topic 12
JavaBeans
Kinds of Properties (I)
ICS 123
• Simple properties: a single value P of some type T
public T getP();
public void setP(T newP);
public boolean isP();
// same as getP when T is boolean
• Indexed properties: an array of values
public T[] getP();
public void setP(T[] newP);
public T getP(int index);
public void setP(int index, T newP);
– Not supported in BDK 1.0
• How does a beanbox know that something is a
simple or indexed property?
16
Topic 12
JavaBeans
Example Simple Properties
ICS 123
public class Airplane extends Label {
protected String serialNumber = "N173UA";
public String getSerialNumber() {
return serialNumber;
}
public Airplane() {
setText(getSerialNumber());
}
protected int flightNumber = 0;
public int getFlightNumber() {
return flightNumber;
}
}
public void setFlightNumber(int n) {
flightNumber = n;
}
• FlightNumber is a read/write property
• SerialNumber is a read-only property
• Attributes storing the property values are made protected
17
Topic 12
JavaBeans
Kinds of Properties (II)
ICS 123
• Bound properties: signal a PropertyChange event
when changed
– One event listener list for all bound properties
– Supported by classes and interfaces in package java.beans
» public class PropertyChangeEvent extends java.util.EventObject
» public interface PropertyChangeListener extends EventListener
» class PropertyChangeSupport implements Serializable
public void addPropertyChangeListener(PropertyChangeListener l);
public void removePropertyChangeListener(PropertyChangeListener l);
• How does a beanbox know that something is a
bound property?
18
Topic 12
JavaBeans
Example Bound Property
import java.beans.*
ICS 123
// Needed for PropertyChange stuff
public class Airplane extends Label {
protected int altitude = 0;
protected PropertyChangeSupport changes =
new PropertyChangeSupport(this);
public int getAltitude() { return altitude; }
public void setAltitude(int a) {
int oldAltitude = altitude;
altitude = a;
changes.firePropertyChange("Altitude", new Integer(oldAltitude),
new Integer(a));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
changes.addPropertyChangeListener(l);
}
}
19
public void removePropertyChangeListener(PropertyChangeListener l) {
changes.removePropertyChangeListener(l);
}
Topic 12
JavaBeans
Kinds of Properties (III)
ICS 123
• Constrained properties: changes can be vetoed by
other objects
– One event listener list for all constrained properties
– Supported by classes and interfaces in package java.beans
» exception PropertyVetoException
» public interface VetoableChangeListener extends EventListener
» class VetoableChangeSupport implements Serializable
public void setP(T newP) throws PropertyVetoException;
public void addVetoableChangeListener(VetoableChangeListener l);
public void removeVetoableChangeListener(VetoableChangeListener l);
– Usually also implemented as bound properties
» Bound property listeners also get notified of changes to
constrained properties
» Only registered vetoers are given the opportunity to veto a change
20
Example Constrained
Property
public class Airplane extends Label {
protected int heading = 0;
protected VetoableChangeSupport vetoes =
new VetoableChangeSupport(this);
Topic 12
JavaBeans
ICS 123
public int getHeading() { return heading; }
public void setHeading(int h) throws PropertyVetoException {
int oldHeading = heading;
vetoes.fireVetoableChange("Heading", new Integer(oldHeading),
new Integer(h)); // *****
heading = h;
changes.firePropertyChange("Heading", new Integer(oldHeading),
new Integer(h));
}
public void addVetoableChangeListener(VetoableChangeListener l) {
vetoes.addVetoableChangeListener(l);
}
}
public void removeVetoableChangeListener(VetoableChangeListener l) {
vetoes.removeVetoableChangeListener(l);
}
• This is also a bound property (using the setup for Altitude)
• PropertyVetoException would be raised within call at *****
21
Topic 12
JavaBeans
JAR Files
ICS 123
• JAR archives contain files related to a bean
–
–
–
–
–
–
22
.class files
.ser files (serialized Beans)
.html files
image files
audio files
Manifest file
» Manifest entries can include several fields, including an optional
indication of whether or not a file is a bean
» In the absence of a manifest file, all .class and .ser files are treated
as beans
Topic 12
JavaBeans
Packaging the Airplane Bean
ICS 123
Create a MANIFEST file
Name: Airplane.class
Java-Bean: True
Name: AirplaneBeanInfo.class
Java-Bean: False
Name: Airplane.gif
Create the JAR file
jar cfm Airplane.jar MANIFEST Airplane.class \
AirplaneBeanInfo.class Airplane.gif
– The jar command creates a file called META-INF/MANIFEST in the .jar
file it creates, using the information contained in MANIFEST above
23
Topic 12
JavaBeans
BDK Directory Structure
ICS 123
<root-directory>
GNUmakefile
beanbox
docs
jars
…
• Run beanbox from beanbox directory
– run.sh in UNIX, run.bat in Windows
• Beanbox looks in jars directory for .jar files
• Look at GNUmakefile for ideas on how to automate creation
of beans
• Lots of documentation in docs directory
24
Topic 12
JavaBeans
The BDK Beanbox
ICS 123
• A simple beanbox for graphically composing beans
and testing bean interactions
• Three windows
– Beanbox: A canvas where beans are placed and wired together
– Toolbox: A palette of available beans
– Property sheet: Properties of the selected bean
• The beanbox finds read-only and write-only
properties for a bean but by default doesn’t display
them in the property sheet for the bean
25
The BDK Beanbox with the
Airplane Bean
Topic 12
JavaBeans
ICS 123
Property Sheet
Beanbox
Toolbox
26
Additional BDK Beanbox
Expectations
Topic 12
JavaBeans
ICS 123
• Each bean class needs a zero-argument constructor
method
– The beanbox calls this method when you drop a bean in the beanbox
• Helpful to define a package for all classes related to
a bean
27
Wiring Beans Together in the
BDK Beanbox
Topic 12
JavaBeans
ICS 123
• Beanbox customizes Edit menu according to
capabilities of currently selected bean
• Wiring events
– Event from generated bean passed as argument to method of target
bean
» Predefined events for the bean’s class
• Component, container, key, mouse, focus, mouseMotion events
» PropertyChange events
» VetoableChange events
» Any other events generated by the bean
• Wiring bound properties
– Change in bound property in one bean can be bound to a property in
another bean
28
Topic 12
JavaBeans
Wiring Up Two Beans (I)
ICS 123
• An Airplane bean and a
Juggler bean
• Airplane is currently selected
29
Topic 12
JavaBeans
Wiring Up Two Beans (II)
ICS 123
• Select propertyChange
event in Airplane bean
30
Topic 12
JavaBeans
Wiring Up Two Beans (III)
ICS 123
• Wire the propertyChange
event to the Juggler
31
Topic 12
JavaBeans
Wiring Up Two Beans (IV)
ICS 123
• Have the juggler’s
startJuggling method called
upon receiving the
Airplane’s propertyChange
event
32
Topic 12
JavaBeans
Wiring Up Two Beans (V)
ICS 123
• Juggler is now selected
• Select mouseClicked event
in Juggler bean
33
Topic 12
JavaBeans
Wiring Up Two Beans (VI)
• Wire the Juggler’s
ICS 123
mouseClicked event to itself
34
Topic 12
JavaBeans
Wiring Up Two Beans (VII)
ICS 123
• Have the juggler’s
stopJuggling method called
upon receiving its own
mouseClicked event
35
Topic 12
JavaBeans
Wiring Up Two Beans (VIII)
ICS 123
• Everything is now wired up
– Click on the Juggler to stop its
juggling
– Change the altitude of the airplane
to start the Juggler juggling
36