Sie sind auf Seite 1von 62

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
Properties
• Use screen captures from Windows customizes selected
bean.
– Start application, following appears:

Method Tracer displays


debugging messages (not
ToolBox has 16 sample discussed)
JavaBeans 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>
HTML file
5 <body>
6 <h1>Test for OurJuggler as an APPLET</h1>
7 This is an example of the use of the generated 1. archive
8 OurJuggler applet. Notice the Applet tag requires several
9 archives, one per JAR used in building the Applet
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>
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 // Fig. 25.22: LogoAnimator.java
2 // Animation bean
3 package jhtp3beans; JavaBean classes are normally packaged.
4
5 import java.awt.*; 1. package statement
6 import java.awt.event.*; Allows persistence, so
7 import java.io.*; JavaBean can be written
8 import java.net.*;
and saved. 2. implements
9 import javax.swing.*; Serializable
10
11 public class LogoAnimator extends JPanel
12 implements ActionListener, Serializable {
13 protected ImageIcon images[];
14 protected int totalImages = 30,
15 currentImage = 0,
16 animationDelay = 50; // 50 millisecond delay
17 protected Timer animationTimer;
18
19 public LogoAnimator()
20 {
21 setSize( getPreferredSize() );
22
23 images = new ImageIcon[ totalImages ];
24
25 URL url;
26
27 for ( int i = 0; i < images.length; ++i ) {
28 url = getClass().getResource(
29 "deitel" + i + ".gif" );
30 images[ i ] = new ImageIcon( url );
31 }
32
33 startAnimation();
34 }
35
36 public void paintComponent( Graphics g )
37 {
38 super.paintComponent( g );
39
40 if ( images[ currentImage ].getImageLoadStatus() ==
41 MediaTracker.COMPLETE ) {
42 g.setColor( getBackground() );
43 g.drawRect(
44 0, 0, getSize().width, getSize().height );
45 images[ currentImage ].paintIcon( this, g, 0, 0 );
46 currentImage = ( currentImage + 1 ) % totalImages;
47 }
48 }
49
50 public void actionPerformed( ActionEvent e )
51 {
52 repaint();
53 }
54
55 public void startAnimation()
56 {
57 if ( animationTimer == null ) {
58 currentImage = 0;
59 animationTimer = new Timer( animationDelay, this );
60 animationTimer.start();
61 }
62
63 else // continue from last image displayed
64 if ( ! animationTimer.isRunning() )
65 animationTimer.restart();
66 }
67
68 public void stopAnimation()
69 {
70 animationTimer.stop();
71 }
72
73 public Dimension getMinimumSize()
74 {
75 return getPreferredSize();
76 }
77
78 public Dimension getPreferredSize()
79 {
80 return new Dimension( 160, 80 );
81 }
82
83 public static void main( String args[] )
84 {
85 LogoAnimator anim = new LogoAnimator();
86
87 JFrame app = new JFrame( "Animator test" );
88 app.getContentPane().add( anim, BorderLayout.CENTER );
89
90 app.addWindowListener(
91 new WindowAdapter() {
92 public void windowClosing( WindowEvent e )
93 {
94 System.exit( 0 );
95 }
96 }
97 );
98
99 app.setSize( anim.getPreferredSize().width + 10,
100 anim.getPreferredSize().height + 30 );
101 app.show();
102 }
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 jar tvf
4852 Thu Feb 15 00:58:00 EST 1996 jhtp3beans/deitel12.gif LogoAnimator.jar
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
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
1. extends
5 import java.awt.*;
LogoAnimator
6 import java.awt.event.*;
7 import javax.swing.*;
8 2.
9 public class LogoAnimator2 extends LogoAnimator { setAnimationDelay
10 // the following two methods are
11 // for the animationDelay property
3.
12 public void setAnimationDelay( int value )
getAnimationDelay
13 {
14 animationDelay = value;
Methods must follow format.
15
16 animationTimer.setDelay( animationDelay );
17 }
18
19 public int getAnimationDelay()
20 {
21 return animationTimer.getDelay();
22 }
23
24 public static void main( String args[] )
25 {
26 LogoAnimator2 anim = new LogoAnimator2();
27
28 JFrame app = new JFrame( "Animator test" );
29 app.getContentPane().add( anim, BorderLayout.CENTER );
30
31 app.addWindowListener(
32 new WindowAdapter() {
33 public void windowClosing( WindowEvent e )
34 {
35 System.exit( 0 );
36 }
37 }
38 );
39
40 app.setSize( anim.getPreferredSize().width + 10,
41 anim.getPreferredSize().height + 30 );
42 app.show();
43 }
44 }
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 slider.addChangeListener(
41 new ChangeListener() {
42 public void stateChanged( ChangeEvent e )
43 {
44 setCurrentValue( slider.getValue() );
45 }
46 }
47 );

– Register ChangeListener
• When changed, calls setCurrentValue
• Notifies registered PropertyChangeListeners
Creating a JavaBean with a Bound Property

61 public void addPropertyChangeListener(


62 PropertyChangeListener listener )
63 {
64 changeSupport.addPropertyChangeListener( listener );
65 }
66
67 public void removePropertyChangeListener(
68 PropertyChangeListener listener )
69 {
70 changeSupport.removePropertyChangeListener( listener );
71 }

– 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 public void setCurrentValue( int current )


107 {
112 changeSupport.firePropertyChange(
113 "currentValue", new Integer( oldValue ),
114 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 // Fig. 25.33: SliderFieldPanel.java
2 // A subclass of JPanel containing a JSlider and a JTextField
3 package jhtp3beans;
4
5 import javax.swing.*;
1. package
6 import javax.swing.event.*;
7 import java.io.*;
8 import java.awt.*; 1.1 extends JPanel
9 import java.awt.event.*;
10 import java.beans.*;
11 1.2 Declarations
12 public class SliderFieldPanel extends JPanel
13 implements Serializable {
14 private JSlider slider;
1.3 Constructor
15 private JTextField field;
16 private Box boxContainer; 1.4 PropertyChange
17 private int currentValue; Create new object, used Support
18 to register change
19 // object to support bound property changes
listeners.
20 private PropertyChangeSupport changeSupport; 1.5 GUI
21
22 public SliderFieldPanel()
23 {
24 // create PropertyChangeSupport for bound properties
25 changeSupport = new PropertyChangeSupport( this );
26
27 slider =
28 new JSlider( SwingConstants.HORIZONTAL, 1, 100, 1 );
29 field = new JTextField(
30 String.valueOf( slider.getValue() ), 5 );
31
32 boxContainer = new Box( BoxLayout.X_AXIS );
33 boxContainer.add( slider );
34 boxContainer.add( Box.createHorizontalStrut( 5 ) );
35 boxContainer.add( field ); 1.6 Event handlers
36
37 setLayout( new BorderLayout() );
38 add( boxContainer );
39
40 slider.addChangeListener(
41 new ChangeListener() {
42 public void stateChanged( ChangeEvent e )
43 {
44 setCurrentValue( slider.getValue() );
45 }
46 } Call method setCurrentValue
47 ); when value changes.
48
49 field.addActionListener(
50 new ActionListener() {
51 public void actionPerformed( ActionEvent e )
52 {
53 setCurrentValue(
54 Integer.parseInt( field.getText() ) );
55 }
56 }
57 );
58 }
59
60 // methods for adding and removing PropertyChangeListeners
61 public void addPropertyChangeListener(
62 PropertyChangeListener listener )
63 {
64 changeSupport.addPropertyChangeListener( listener ); 2.
65 }
addPropertyChange
66
67 public void removePropertyChangeListener(
Methods to support registration.
Listener
68 PropertyChangeListener listener )
Methods must have this naming.
69 { 3. removeProperty
70 changeSupport.removePropertyChangeListener( listener ); ChangeListener
71 }
72
73 // property minimumValue
74 public void setMinimumValue( int min )
75 {
76 slider.setMinimum( min );
77
78 if ( slider.getValue() < slider.getMinimum() ) {
79 slider.setValue( slider.getMinimum() );
80 field.setText( String.valueOf( slider.getValue() ) );
81 }
82 }
83
84 public int getMinimumValue()
85 {
86 return slider.getMinimum();
87 }
88
89 // property maximumValue
90 public void setMaximumValue( int max )
91 {
92 slider.setMaximum( max );
93 4. setCurrentValue
94 if ( slider.getValue() > slider.getMaximum() ) {
95 slider.setValue( slider.getMaximum() );
96 field.setText( String.valueOf( slider.getValue() ) ); 4.1
97 } firePropertyChange
98 }
99
100 public int getMaximumValue() 5. getCurrentValue
101 {
102 return slider.getMaximum();
103 }
104
105 // property currentValue
106 public void setCurrentValue( int current )
107 {
108 int oldValue = currentValue;
109 currentValue = current; Pass name, old value,
110 slider.setValue( currentValue );
and new value. This
111 field.setText( String.valueOf( currentValue ) );
112 changeSupport.firePropertyChange( notifies registered
113 "currentValue", new Integer( oldValue ), listeners of change.
114 new Integer( currentValue ) );
115 }
116
117 public int getCurrentValue()
118 {
119 return slider.getValue();
120 }
121
122 // property fieldWidth
123 public void setFieldWidth( int cols )
124 {
125 field.setColumns( cols ); 6. set/get methods
126 boxContainer.validate();
127 }
128
129 public int getFieldWidth()
130 {
131 return field.getColumns();
132 }
133
134 public Dimension getMinimumSize()
135 {
136 return boxContainer.getMinimumSize();
137 }
138
139 public Dimension getPreferredSize()
140 {
141 return boxContainer.getPreferredSize();
142 }
143 }
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 public final static Class beanClass =
9 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 public PropertyDescriptor[] getPropertyDescriptors()
12 {
14 PropertyDescriptor fieldWidth =
15 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 return 1;
42 }

– 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 EventSetDescriptor changed =
47 new EventSetDescriptor( beanClass,
48 "propertyChange",
49 java.beans.PropertyChangeListener.class,
50 "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 changed.setDisplayName(
53 "SliderFieldPanel value changed" );

– Class EventSetDescriptor
– Method setDisplayName( stringName )
• Specifies name for event set in builder tool
1 // Fig. 25.38: SliderFieldPanelBeanInfo.java
Same package
2 // The BeanInfo class for SliderFieldPanel as bean.
Extend SimpleBeanInfo class, with
3 package jhtp3beans; default implementation of BeanInfo
4 interface.
5 import java.beans.*; 1. package
6
7 public class SliderFieldPanelBeanInfo extends SimpleBeanInfo { 1.1 import
8 public final static Class beanClass = Create Class object, provides
9 SliderFieldPanel.class; access to class
10 Specify properties that can be 1.2 definition.
extends
11 public PropertyDescriptor[]exposed by builder.
getPropertyDescriptors() SimpleBeanInfo
12 {
13 try { 1.3 Class
14 PropertyDescriptor fieldWidth =
15 new PropertyDescriptor( "fieldWidth", beanClass );
16 PropertyDescriptor currentValue =
2. getProperty
17 new PropertyDescriptor(
Descriptors
18 "currentValue", beanClass );
19 PropertyDescriptor maximumValue = 2.1 setBound
20 new PropertyDescriptor(
21 "maximumValue", beanClass );
22 PropertyDescriptor minimumValue =
23 Specify bound
new PropertyDescriptor( "minimumValue", beanClass ); property.
24
25 // ensure PropertyChangeEvent occurs for this property
26 currentValue.setBound( true );
27
28 PropertyDescriptor descriptors[] = { fieldWidth,
29 currentValue, maximumValue, minimumValue };
30
31 return descriptors;
32 } 3.
33 catch ( IntrospectionException ie ) { getDefaultProperty
34 throw new RuntimeException( ie.toString() );
Index
Get array index of default property
35 }
36 } (currentValue).
37 4. getEventSet
38 // the index for the currentValue property Descriptors
39 public int getDefaultPropertyIndex()
40 {
4.1 Constructor
41 return 1;
42 }
43 4.2 setDisplayName
44 public EventSetDescriptor[] getEventSetDescriptors() {
Describes events supported
45 try {
by bean.
46 EventSetDescriptor changed =
47 new EventSetDescriptor( beanClass,
48 "propertyChange",
49 java.beans.PropertyChangeListener.class,
50 "propertyChange"); Set title of event in
51 builder.
52 changed.setDisplayName(
53 "SliderFieldPanel value changed" );
54
55 EventSetDescriptor[] descriptors = { changed };
56
57 return descriptors;
58 }
59 catch (IntrospectionException e) {
60 throw new RuntimeException(e.toString());
61 }
62 }
63 }

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

Das könnte Ihnen auch gefallen