close

Se connecter

Se connecter avec OpenID

Chapter 25 - JavaBeans

IntégréTéléchargement
JavaBeans
Definition: What is a Bean?
If you have used Delphi, or Visual Basic, you are already familiar with the notion of a bean. The idea
is the same; the programming language is different. A Java Bean is a reusable software component
that works with Java. More specifically: a Java Bean is a reusable software component that can be
visually manipulated in builder tools.
•
Definition: A Java Bean is a reusable software component that can be visually
manipulated in builder tools.
Introduction
• JavaBeans (beans)
– Reusable software component model
– Assemble predefined components
• Create powerful applications and applets
– Graphical programming and design environments
• Builder tools
• Support beans, reuse and integrate components
– Component assembler
• Programmer who use defined components
– Work on design of GUI and functionality
• Do not need to know implementation
– Just need to know services
Introduction
• Example of bean concept
– Have animation bean
• Want two buttons, start and stop
– With beans, can "hook up" buttons to startAnimation
and stopAnimation methods
• When pressed, method called
• Builder tool does work
– Use previously defined, reusable components
– Little or no code must be written
• Component assembler can "connect the dots"
– More info about beans at
• http://java.sun.com/beans/
BeanBox Overview
• BeanBox installation
– Free utility from JavaBeans Development Kit (BDK)
http://java.sun.com/beans/software/index.html
• Windows, Solaris, and platform independent versions
• In Windows version, minor bug
– Do not install in directory with spaces in name
• To run, go to install directory, beanbox subdirectory, load
run.bat (or run.sh)
• BeanBox test container for JavaBeans
– Preview how bean will be displayed
– Not meant to be robust development tool
BeanBox Overview
• Use screen captures from Windows
– Start application, following appears:
ToolBox has 16 sample
JavaBeans
Properties
customizes selected
bean.
Method Tracer displays
debugging messages (not
discussed)
BeanBox window tests beans.
Background currently selected
(dashed box).
BeanBox Overview
– Initially, background selected
• Customize in Properties box
BeanBox Overview
– Now, add JavaBean in BeanBox window
• Click ExplicitButton bean in ToolBox window
– Functions as a JButton
• Click crosshair where center of button should appear
• Change label to "Start the Animation"
BeanBox Overview
– Select button (if not selected) and move to corner
• Position mouse on edges, move cursor appears
• Drag to new location
– Resize button
• Put mouse in corner, resize cursor
• Drag mouse to change size
BeanBox Overview
– Add another button (same steps)
• "Stop the Animation"
– Add animation bean
• In ToolBox, select Juggler and add to BeanBox
• Animation begins immediately
Properties for juggler.
BeanBox Overview
– Now, "hook up" events from buttons
• Start and stop animation
– Edit menu
• Access to events from beans that are an event source (bean can
notify listener)
• Swing GUI components are beans
• Select "Stop the Animation"
• Edit->Events->button push -> actionPerformed
BeanBox Overview
– Line appears from button to mouse
• Target selector - target of event
– Object with method we intend to call
– Connect the dots programming
• Click on Juggler, brings up EventTargetDialog
– Shows public methods
– Select stopJuggling
BeanBox Overview
– Event hookup complete
• Writes new hookup/event adapter class
• Object of class registered as actionListener fro button
• Can click button to stop animation
– Repeat for "Start the Animation" button
• Method startAnimation
BeanBox Overview
• Save as design
– Can reloaded into BeanBox later
– Can have any file extension
• Opening
– Applet beans (like Juggler) begin executing immediately
BeanBox Overview
• Save as Java Applet
– File->Make Applet
• Stores .class file in .jar (Java Archive File)
• Can rename and change directory
BeanBox Overview
• To run applet
– Go to command line, go to directory where applet saved
– Should be .html file, load into appletviewer
• Background not yellow
• BeanBox container not saved as part of applet
• Applet is a container, can hold beans
– Archive property of <applet> tag
• Comma separated list of .jar files used
• .jar files for beans listed
• Source code in AppletName_files directory
1
<html>
2
<head>
3 <title>Test page for OurJuggler as an APPLET</Title>
4
</head>
5
<body>
6
<h1>Test for OurJuggler as an APPLET</h1>
7
This is an example of the use of the generated
8
OurJuggler applet.
9
archives, one per JAR used in building the Applet
HTML file
Notice the Applet tag requires several
10 <p>
11 <applet
12
archive="./OurJuggler.jar,./support.jar
13
,./juggler.jar
14
,./buttons.jar
15
"
16
code="OurJuggler"
17
width=382
18
height=150
19 >
20 Trouble instantiating applet OurJuggler!!
21 </applet>
1. archive
Program Output
Preparing a Class to Be a JavaBean
• Example
– Animation of Deitel & Associates, Inc. logo (as in Chapter
16)
• Before, stand-alone application in a JFrame
• Now, stand-alone application and as bean
– Application extends JPanel
• When loaded into BeanBox, can us predefined properties and
events (background color, mouse events)
– Code same as example in Chapter 16 except for two minor
modifications
Preparing a Class to Be a JavaBean
• Minor modifications
– Classes representing a bean placed into package
• Compile with -d option
• javac -d . LogoAnimator.java
– "." represents current directory (where to place package)
– After compiled, wrap class into JavaBean with jar utility
» Next section
– Implement Serializable interface
• Persistence - save bean for future use
• Can be serialized with ObjectOutputStreams and
ObjectInputStreams
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 25.22: LogoAnimator.java
// Animation bean
package jhtp3beans;
JavaBean
import
import
import
import
import
java.awt.*;
java.awt.event.*;
java.io.*;
java.net.*;
javax.swing.*;
classes are normally packaged.
Allows persistence, so
JavaBean can be written
and saved.
public class LogoAnimator extends JPanel
implements ActionListener, Serializable {
protected ImageIcon images[];
protected int totalImages = 30,
currentImage = 0,
animationDelay = 50; // 50 millisecond delay
protected Timer animationTimer;
public LogoAnimator()
{
setSize( getPreferredSize() );
images = new ImageIcon[ totalImages ];
URL url;
for ( int i = 0; i < images.length; ++i ) {
url = getClass().getResource(
"deitel" + i + ".gif" );
images[ i ] = new ImageIcon( url );
}
1. package statement
2. implements
Serializable
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
startAnimation();
}
public void paintComponent( Graphics g )
{
super.paintComponent( g );
if ( images[ currentImage ].getImageLoadStatus() ==
MediaTracker.COMPLETE ) {
g.setColor( getBackground() );
g.drawRect(
0, 0, getSize().width, getSize().height );
images[ currentImage ].paintIcon( this, g, 0, 0 );
currentImage = ( currentImage + 1 ) % totalImages;
}
}
public void actionPerformed( ActionEvent e )
{
repaint();
}
public void startAnimation()
{
if ( animationTimer == null ) {
currentImage = 0;
animationTimer = new Timer( animationDelay, this );
animationTimer.start();
}
62
63
64
else // continue from last image displayed
if ( ! animationTimer.isRunning() )
65
animationTimer.restart();
66
67
}
68
69
public void stopAnimation()
{
70
71
}
72
73
74
public Dimension getMinimumSize()
{
75
76
77
78
animationTimer.stop();
return getPreferredSize();
}
80
81
public Dimension getPreferredSize()
{
return new Dimension( 160, 80 );
}
82
83
84
public static void main( String args[] )
{
79
85
86
LogoAnimator anim = new LogoAnimator();
87
88
JFrame app = new JFrame( "Animator test" );
app.getContentPane().add( anim, BorderLayout.CENTER );
89
90
91
92
93
94
95
96
97
98
99
100
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
101
app.show();
102
app.setSize( anim.getPreferredSize().width + 10,
anim.getPreferredSize().height + 30 );
}
103 }
Program Output
Creating a JavaBean: Java Archive Files and
the jar Utility
• Place class in Java Archive file (JAR)
– Create text file manifest.tmp
• Manifest file describes contents of JAR file
• jar utility uses manifest.tmp
– Creates MANIFEST.MF in META-INF directory
– Used by development environments
– Can execute application from JAR file with java interpreter
• Specify class with main
Creating a JavaBean: Java Archive Files and
the jar Utility
1 Main-Class: jhtp3beans.LogoAnimator
2
3 Name: jhtp3beans/LogoAnimator.class
4 Java-Bean: True
– Manifest file for LogoAnimator
• Specify class with main, runs bean as application
– java -jar LogoAnimator.jar
• Run application from bean
• Interpreter looks at manifest file
– Executes main of Main-Class
java. -cp LogoAnimator.jar jhtp3beans.LogoAnimator
– cp - class path, JAR file to look for classes
– Followed by application class (explicit name, with package)
Creating a JavaBean: Java Archive Files and
the jar Utility
1 Main-Class: jhtp3beans.LogoAnimator
2
3 Name: jhtp3beans/LogoAnimator.class
4 Java-Bean: True
– Name: name of file with bean class (full package and class
name)
• Dots . used in package named replaced with /
– Java-Bean: true - file is a JavaBean
• Possible to have non-JavaBean in JAR file
• Used to support JavaBeans
– Each class separated by blank line
• Java-Bean: immediately follows Name:
Creating a JavaBean: Java Archive Files and
the jar Utility
• Create JAR file
– jar utility at command line
jar cfm LogoAnimator.jar manifest.tmp jhtp3beans\*.*
– Options
• c - creating JAR file
• f - indicates next argument is name of file
• m - next argument manifest.tmp file
– Used to create MANIFEST.MF
– Next, list files to be included in JAR file
• Directory structure of JAR file should match manifest.tmp
Creating a JavaBean: Java Archive Files and
the jar Utility
• To confirm files were archived
– jar tvf LogoAnimator.jar
– Options
• t - list table of contents
• v - verbose mode
• f - next argument is JAR file to use
– Execute LogoAnimator application
java -jar LogoAnimator.jar
0 Sun Mar 14 11:36:16 EST 1999 META-INF/
163 Sun Mar 14 11:36:16 EST 1999 META-INF/MANIFEST.MF
4727 Thu Feb 15 00:37:04 EST 1996 jhtp3beans/deitel0.gif
4858 Thu Feb 15 00:39:32 EST 1996 jhtp3beans/deitel1.gif
4374 Thu Feb 15 00:55:46 EST 1996 jhtp3beans/deitel10.gif
4634 Thu Feb 15 00:56:52 EST 1996 jhtp3beans/deitel11.gif
4852 Thu Feb 15 00:58:00 EST 1996 jhtp3beans/deitel12.gif
4877 Thu Feb 15 00:59:10 EST 1996 jhtp3beans/deitel13.gif
4926 Thu Feb 15 01:00:20 EST 1996 jhtp3beans/deitel14.gif
4765 Thu Feb 15 01:01:32 EST 1996 jhtp3beans/deitel15.gif
4886 Thu Feb 15 01:05:16 EST 1996 jhtp3beans/deitel16.gif
4873 Thu Feb 15 01:06:12 EST 1996 jhtp3beans/deitel17.gif
4739 Thu Feb 15 01:07:18 EST 1996 jhtp3beans/deitel18.gif
4566 Thu Feb 15 01:08:24 EST 1996 jhtp3beans/deitel19.gif
4819 Thu Feb 15 00:41:06 EST 1996 jhtp3beans/deitel2.gif
4313 Thu Feb 15 01:09:48 EST 1996 jhtp3beans/deitel20.gif
3910 Thu Feb 15 01:10:46 EST 1996 jhtp3beans/deitel21.gif
3076 Thu Feb 15 01:12:02 EST 1996 jhtp3beans/deitel22.gif
3408 Thu Feb 15 01:13:16 EST 1996 jhtp3beans/deitel23.gif
4039 Thu Feb 15 01:14:06 EST 1996 jhtp3beans/deitel24.gif
4393 Thu Feb 15 01:15:02 EST 1996 jhtp3beans/deitel25.gif
4626 Thu Feb 15 01:16:06 EST 1996 jhtp3beans/deitel26.gif
4852 Thu Feb 15 01:17:18 EST 1996 jhtp3beans/deitel27.gif
4929 Thu Feb 15 01:18:18 EST 1996 jhtp3beans/deitel28.gif
4914 Thu Feb 15 01:19:16 EST 1996 jhtp3beans/deitel29.gif
4769 Thu Feb 15 00:42:52 EST 1996 jhtp3beans/deitel3.gif
4617 Thu Feb 15 00:43:54 EST 1996 jhtp3beans/deitel4.gif
4335 Thu Feb 15 00:47:14 EST 1996 jhtp3beans/deitel5.gif
3967 Thu Feb 15 00:49:40 EST 1996 jhtp3beans/deitel6.gif
3200 Thu Feb 15 00:50:58 EST 1996 jhtp3beans/deitel7.gif
3393 Thu Feb 15 00:52:32 EST 1996 jhtp3beans/deitel8.gif
4006 Thu Feb 15 00:53:48 EST 1996 jhtp3beans/deitel9.gif
420 Sun Mar 14 11:36:16 EST 1999 jhtp3beans/LogoAnimator$1.class
3338 Sun Mar 14 11:36:16 EST 1999 jhtp3beans/LogoAnimator.class
jar tvf
LogoAnimator.jar
Adding Beans to the BeanBox
• Using Beans
– LogoAnimator is wrapped in a JAR file as a JavaBean
• Can use in BeanBox
– Two ways to load bean
• Put JAR file in BDK1.1\jars directory
– Loaded into toolbox
• Use File -> LoadJar
Adding Beans to the BeanBox
• To add to design area
– Click bean in ToolBox
– Click crosshair where bean should appear
Adding Beans to the BeanBox
• Properties window
– Shows properties of LogoAnimator
• Properties inherited from JPanel
Connecting Beans with Events in the
BeanBox
• Connecting Beans with events
– LogoAnimator has methods stopAnimation and
startAnimation
– Connect two ExplicitButtons to LogoAnimator
• Change label
• Edit -> Events -> button push -> actionPerformed
Adding Properties to a JavaBean
• Add animationDelay property
– Control animation speed
– Extend LogoAnimator and create LogoAnimator2
– Read/write property of bean
• Defined as set/get method pair of format:
public void setPropertyName( DataType value )
public DataType getPropertyName()
• Property set and get methods
• If using boolean, use isPropertyName() instead of get
– We use setAnimationDelay and
getAnimationDelay
1
// Fig. 25.30: LogoAnimator2.java
2
// Animation bean with animationDelay property
3
package jhtp3beans;
4
5
import java.awt.*;
6
import java.awt.event.*;
7
import javax.swing.*;
8
9
public class LogoAnimator2 extends LogoAnimator {
10
// the following two methods are
11
// for the animationDelay property
12
public void setAnimationDelay( int value )
13
{
14
animationDelay = value;
15
16
17
animationTimer.setDelay( animationDelay );
}
18
19
public int getAnimationDelay()
20
{
21
22
return animationTimer.getDelay();
}
23
24
public static void main( String args[] )
25
{
26
LogoAnimator2 anim = new LogoAnimator2();
1. extends
LogoAnimator
2.
setAnimationDelay
3.
getAnimationDelay
Methods must follow format.
27
28
JFrame app = new JFrame( "Animator test" );
29
app.getContentPane().add( anim, BorderLayout.CENTER );
30
31
app.addWindowListener(
32
new WindowAdapter() {
33
34
public void windowClosing( WindowEvent e )
{
35
System.exit( 0 );
36
}
37
}
38
);
39
40
app.setSize( anim.getPreferredSize().width + 10,
41
anim.getPreferredSize().height + 30 );
42
43
44 }
app.show();
}
Adding Properties to a JavaBean
• Properties
– When builder tool examines bean, looks for pairs of set/get
methods
• Introspection
• If found, used as property
• Creating bean
– Must wrap LogoAnimator2 class
– Compile: javac -d . LogoAnimator2.java
– Create manifest.tmp
1 Main-Class: jhtp3beans.LogoAnimator2
2
3 Name: jhtp3beans/LogoAnimator2.class
4 Java-Bean: True
Adding Properties to a JavaBean
• Creating bean
– Package into JAR file
jar cfm LogoAnimator2.jar manifest.tmp jhtp3beans\*.*
– Load LogoAnimator2 bean, can change
animationDelay property
Creating a JavaBean with a Bound Property
• Bound property
– Other objects notified when it changes
– Use event handling
• Registered PropertyChangeListeners notified when
value changes
– java.beans package
• Class PropertyChangeEvent,
PropertyChangeListener
• Example
– Create custom GUI component SliderFieldPanel
• Has a JTextField linked to a JSlider
• Changes affect them both
Creating a JavaBean with a Bound Property
• Example
– Want to link this to LogoAnimator2
• Want SliderFieldPanel to control animation speed
3 package jhtp3beans;
– Use same package
12 public class SliderFieldPanel extends JPanel
13
implements Serializable {
– Subclass of JPanel, can add JSlider and JTextField
Creating a JavaBean with a Bound Property
25
changeSupport = new PropertyChangeSupport( this );
– Create object
• argument (this) - source of PropertyChangeEvent
40
41
42
43
44
45
46
47
slider.addChangeListener(
new ChangeListener() {
public void stateChanged( ChangeEvent e )
{
setCurrentValue( slider.getValue() );
}
}
);
– Register ChangeListener
• When changed, calls setCurrentValue
• Notifies registered PropertyChangeListeners
Creating a JavaBean with a Bound Property
61
62
63
64
65
66
67
68
69
70
71
public void addPropertyChangeListener(
PropertyChangeListener listener )
{
changeSupport.addPropertyChangeListener( listener );
}
public void removePropertyChangeListener(
PropertyChangeListener listener )
{
changeSupport.removePropertyChangeListener( listener );
}
– Help register ChangeListeners
• Supply listener interface and event class
• Must have methods for adding/removing listeners
• Use this naming for bound property events
Creating a JavaBean with a Bound Property
106
107
112
113
114
public void setCurrentValue( int current )
{
changeSupport.firePropertyChange(
"currentValue", new Integer( oldValue ),
new Integer( currentValue ) );
– currentValue - bound property
• setCurrentValue, getCurrentValue
• When changes, must notify registered
PropertyChangeListeners
– Method firePropertyChange( propertyName,
oldValue, newValue );
• Of PropertyChangeSupport
• Notifies registered listeners
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 25.33: SliderFieldPanel.java
// A subclass of JPanel containing a JSlider and a JTextField
package jhtp3beans;
import
import
import
import
import
import
javax.swing.*;
javax.swing.event.*;
java.io.*;
java.awt.*;
java.awt.event.*;
java.beans.*;
1. package
1.1 extends JPanel
1.2 Declarations
public class SliderFieldPanel extends JPanel
implements Serializable {
private JSlider slider;
private JTextField field;
private Box boxContainer;
private int currentValue;
Create new object,
1.3 Constructor
used
1.4 PropertyChange
Support
to register change
// object to support bound property changes
listeners.
private PropertyChangeSupport changeSupport;
public SliderFieldPanel()
{
// create PropertyChangeSupport for bound properties
changeSupport = new PropertyChangeSupport( this );
slider =
new JSlider( SwingConstants.HORIZONTAL, 1, 100, 1 );
field = new JTextField(
String.valueOf( slider.getValue() ), 5 );
1.5 GUI
31
32
boxContainer = new Box( BoxLayout.X_AXIS );
33
boxContainer.add( slider );
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
boxContainer.add( Box.createHorizontalStrut( 5 ) );
boxContainer.add( field );
1.6 Event handlers
setLayout( new BorderLayout() );
add( boxContainer );
slider.addChangeListener(
new ChangeListener() {
public void stateChanged( ChangeEvent e )
{
setCurrentValue( slider.getValue() );
}
}
Call method setCurrentValue
);
when value changes.
field.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
setCurrentValue(
Integer.parseInt( field.getText() ) );
}
}
);
}
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// methods for adding and removing PropertyChangeListeners
public void addPropertyChangeListener(
PropertyChangeListener listener )
{
changeSupport.addPropertyChangeListener( listener );
}
2.
addPropertyChange
Methods to support
registration.
Listener
Methods must have this naming.
public void removePropertyChangeListener(
PropertyChangeListener listener )
{
changeSupport.removePropertyChangeListener( listener );
}
// property minimumValue
public void setMinimumValue( int min )
{
slider.setMinimum( min );
if ( slider.getValue() < slider.getMinimum() ) {
slider.setValue( slider.getMinimum() );
field.setText( String.valueOf( slider.getValue() ) );
}
}
public int getMinimumValue()
{
return slider.getMinimum();
}
3. removeProperty
ChangeListener
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// property maximumValue
public void setMaximumValue( int max )
{
slider.setMaximum( max );
if ( slider.getValue() > slider.getMaximum() ) {
slider.setValue( slider.getMaximum() );
field.setText( String.valueOf( slider.getValue() ) );
}
4. setCurrentValue
4.1
firePropertyChange
}
public int getMaximumValue()
{
return slider.getMaximum();
}
// property currentValue
public void setCurrentValue( int current )
{
int oldValue = currentValue;
currentValue = current;
slider.setValue( currentValue );
field.setText( String.valueOf( currentValue ) );
changeSupport.firePropertyChange(
"currentValue", new Integer( oldValue ),
new Integer( currentValue ) );
}
public int getCurrentValue()
{
return slider.getValue();
}
5. getCurrentValue
Pass name, old value,
and new value. This
notifies registered
listeners of change.
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143 }
// property fieldWidth
public void setFieldWidth( int cols )
{
field.setColumns( cols );
boxContainer.validate();
}
public int getFieldWidth()
{
return field.getColumns();
}
public Dimension getMinimumSize()
{
return boxContainer.getMinimumSize();
}
public Dimension getPreferredSize()
{
return boxContainer.getPreferredSize();
}
6. set/get methods
Creating a JavaBean with a Bound Property
• Create bean
– Compile: javac -d . SliderFieldPanel.java
– Manifest file (manifest.tmp)
1 Name: jhtp3beans/SliderFieldPanel.class
2 Java-Bean: True
• No Main-Class: because not an application
– Archive in JAR file:
jar cfm SliderFieldPanel.jar manifest.tmp jhtp3beans\*.*
Creating a JavaBean with a Bound Property
• Usage
– Add SliderFieldPanel to BeanBox with Juggler
• Set maximumValue to 1000, currentValue to 125
(default animations speed for Juggler)
– Go to Edit->Bind property...
• Click currentValue
Creating a JavaBean with a Bound Property
• Usage
– Red target selector line appears
• Connect to Juggler and click
– PropertyNameDialog
• Shows target properties with same data type as bound property
• Select animationRate (only listed property)
• animationRate bound to currentValue
Specifying the BeanInfo Class for a
JavaBean
• Introspection mechanism
– Used by builder tool
– Exposes bean's properties, methods, and events if
programmer uses design patterns
• I.e., special naming conventions
– Use classes in java.lang.reflect for introspection
– Can customize which methods/events/properties available
• Create class that implements interface BeanInfo
• BeanInfo class has same name as bean, ends in BeanInfo
– SliderFieldPanelBeanInfo.java
• Placed in same package as bean
Specifying the BeanInfo Class for a
JavaBean
7 public class SliderFieldPanelBeanInfo extends SimpleBeanInfo {
– SimpleBeanInfo
• Default implementation of BeanInfo
• Selectively override methods
8
9
public final static Class beanClass =
SliderFieldPanel.class;
– Class Class
• Allows program to refer to class definition
• Refers to class that will be searched for features described in
beanInfo class
• final - will not be modified
• static - only one instance needed
Specifying the BeanInfo Class for a
JavaBean
11
12
14
15
public PropertyDescriptor[] getPropertyDescriptors()
{
PropertyDescriptor fieldWidth =
new PropertyDescriptor( "fieldWidth", beanClass );
– getPropertyDescriptors (overridden)
• Returns array of PropertyDescriptor objects
– Each describes property
– new PropertyDescriptor( "propertyName", beanClass )
• Property must have named set and get methods
26
currentValue.setBound( true );
– setBound( true )
• Specifies property is bound
Specifying the BeanInfo Class for a
JavaBean
39
public int getDefaultPropertyIndex()
40
{
41
42
return 1;
}
– getDefaultPropertyIndex (overridden)
• Returns array index of default property
• In this case, currentValue
44
public EventSetDescriptor[] getEventSetDescriptors() {
– getEventSetDescriptors
• Returns array of EventSetDescriptor objects
• Describes events supported by bean
Specifying the BeanInfo Class for a
JavaBean
46
47
48
49
50
EventSetDescriptor changed =
new EventSetDescriptor( beanClass,
"propertyChange",
java.beans.PropertyChangeListener.class,
"propertyChange");
– Constructor arguments
• 1: Class object, represents event source
• 2: String, event set name
– mouse includes mousePressed, mouseClicked...
– We use propertyChange
• 3: Class object, implemented event listener interface
– Creates anonymous object of class
• 4: String, name of listener method called when event occurs
Specifying the BeanInfo Class for a
JavaBean
52
53
changed.setDisplayName(
"SliderFieldPanel value changed" );
– Class EventSetDescriptor
– Method setDisplayName( stringName )
• Specifies name for event set in builder tool
1
// Fig. 25.38: SliderFieldPanelBeanInfo.java
Same package as
2 // The BeanInfo class for SliderFieldPanel
3
package jhtp3beans;
4
5 import java.beans.*;
bean.
Extend SimpleBeanInfo class, with
default implementation of BeanInfo
interface.
1. package
6
11
1.1 import
public final static Class beanClass =
Create Class object, provides
SliderFieldPanel.class;
access to class
1.2 definition.
extends
Specify properties that can be
SimpleBeanInfo
exposed
by builder.
public PropertyDescriptor[]
getPropertyDescriptors()
12
{
7
8
9
10
13
14
15
16
17
18
19
20
21
22
23
);
24
public class SliderFieldPanelBeanInfo extends SimpleBeanInfo {
1.3 Class
try {
PropertyDescriptor fieldWidth =
new PropertyDescriptor( "fieldWidth", beanClass );
PropertyDescriptor currentValue =
new PropertyDescriptor(
"currentValue", beanClass );
PropertyDescriptor maximumValue =
2.1 setBound
new PropertyDescriptor(
"maximumValue", beanClass );
PropertyDescriptor minimumValue =
new PropertyDescriptor( "minimumValue", beanClass
Specify bound
25
// ensure PropertyChangeEvent occurs for this property
26
currentValue.setBound( true );
27
2. getProperty
Descriptors
property.
28
29
30
31
32
33
34
}
catch ( IntrospectionException ie ) {
throw new RuntimeException( ie.toString() );
35
}
36
PropertyDescriptor descriptors[] = { fieldWidth,
currentValue, maximumValue, minimumValue };
return descriptors;
3.
getDefaultProperty
Index
Get array index of default
property
(currentValue).
}
37
38
// the index for the currentValue property
39
public int getDefaultPropertyIndex()
40
{
41
42
return 1;
45
46
4.2 setDisplayName
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor changed =
47
new EventSetDescriptor( beanClass,
48
"propertyChange",
49
java.beans.PropertyChangeListener.class,
50
"propertyChange");
51
52
53
changed.setDisplayName(
"SliderFieldPanel value changed" );
54
55
4.1 Constructor
}
43
44
4. getEventSet
Descriptors
EventSetDescriptor[] descriptors = { changed };
Describes events supported
by bean.
Set title of event in
builder.
56
57
58
59
60
61
62
63 }
return descriptors;
}
catch (IntrospectionException e) {
throw new RuntimeException(e.toString());
}
}
Program Output
Only the specified properties are listed.
JavaBeans World Wide Web Resources
• Web resources
– http://java.sun.com/beans/
• Download Beans Development Kit, docs
– http://java.sun.com/beans/spec.html
• Specifications
– http://java.sun.com/beans/tools.html
• Beans-enabled development tools
– http://java.sun.com/beans/directory/
• Searchable directory of beans
– http://java.sun.com/products/hotjava/bean/
index.html
• Evaluation version of bean with HTML rendering
Auteur
Document
Catégorie
Uncategorized
Affichages
4
Taille du fichier
821 KB
Étiquettes
1/--Pages
signaler