javabeans. definition: what is a bean? if you have used delphi, or visual basic, you are already...

62
JavaBeans

Post on 22-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

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 BeanBox window tests

beans. Background currently selected (dashed box).

Properties customizes selected bean.

Method Tracer displays debugging messages (not discussed)

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

HTML file

1. archive

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. 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. package statement

2. implements Serializable

1 // Fig. 25.22: LogoAnimator.java2 // Animation bean33 package jhtp3beans;45 import java.awt.*;6 import java.awt.event.*;7 import java.io.*;8 import java.net.*;9 import javax.swing.*;1011 public class LogoAnimator extends JPanel1212 implements ActionListener, Serializable {13 protected ImageIcon images[];14 protected int totalImages = 30,15 currentImage = 0,16 animationDelay = 50; // 50 millisecond delay17 protected Timer animationTimer;1819 public LogoAnimator()20 {21 setSize( getPreferredSize() );2223 images = new ImageIcon[ totalImages ];2425 URL url;2627 for ( int i = 0; i < images.length; ++i ) {28 url = getClass().getResource(29 "deitel" + i + ".gif" );30 images[ i ] = new ImageIcon( url );31 }

JavaBean classes are normally packaged.

Allows persistence, so JavaBean can be written and saved.

34 }3536 public void paintComponent( Graphics g )37 {38 super.paintComponent( g );3940 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 }4950 public void actionPerformed( ActionEvent e )51 {52 repaint();53 }5455 public void startAnimation()56 {57 if ( animationTimer == null ) {58 currentImage = 0; 59 animationTimer = new Timer( animationDelay, this );60 animationTimer.start();61 }

32

33 startAnimation();

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

62

63 else // continue from last image displayed

64 if ( ! animationTimer.isRunning() )

65 animationTimer.restart();

66 }

Program Output

100 anim.getPreferredSize().height + 30 );

101 app.show();

102 }

103}

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,

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

– 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)

1 Main-Class: jhtp3beans.LogoAnimator

2

3 Name: jhtp3beans/LogoAnimator.class

4 Java-Bean: True

Creating a JavaBean: Java Archive Files and the jar Utility

– 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:

1 Main-Class: jhtp3beans.LogoAnimator

2

3 Name: jhtp3beans/LogoAnimator.class

4 Java-Bean: True

Creating a JavaBean: Java Archive Files and the jar Utility

• Create JAR file– jar utility at command linejar 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 applicationjava -jar LogoAnimator.jar

jar tvf 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.MF4727 Thu Feb 15 00:37:04 EST 1996 jhtp3beans/deitel0.gif4858 Thu Feb 15 00:39:32 EST 1996 jhtp3beans/deitel1.gif4374 Thu Feb 15 00:55:46 EST 1996 jhtp3beans/deitel10.gif4634 Thu Feb 15 00:56:52 EST 1996 jhtp3beans/deitel11.gif4852 Thu Feb 15 00:58:00 EST 1996 jhtp3beans/deitel12.gif4877 Thu Feb 15 00:59:10 EST 1996 jhtp3beans/deitel13.gif4926 Thu Feb 15 01:00:20 EST 1996 jhtp3beans/deitel14.gif4765 Thu Feb 15 01:01:32 EST 1996 jhtp3beans/deitel15.gif4886 Thu Feb 15 01:05:16 EST 1996 jhtp3beans/deitel16.gif4873 Thu Feb 15 01:06:12 EST 1996 jhtp3beans/deitel17.gif4739 Thu Feb 15 01:07:18 EST 1996 jhtp3beans/deitel18.gif4566 Thu Feb 15 01:08:24 EST 1996 jhtp3beans/deitel19.gif4819 Thu Feb 15 00:41:06 EST 1996 jhtp3beans/deitel2.gif4313 Thu Feb 15 01:09:48 EST 1996 jhtp3beans/deitel20.gif3910 Thu Feb 15 01:10:46 EST 1996 jhtp3beans/deitel21.gif3076 Thu Feb 15 01:12:02 EST 1996 jhtp3beans/deitel22.gif3408 Thu Feb 15 01:13:16 EST 1996 jhtp3beans/deitel23.gif4039 Thu Feb 15 01:14:06 EST 1996 jhtp3beans/deitel24.gif4393 Thu Feb 15 01:15:02 EST 1996 jhtp3beans/deitel25.gif4626 Thu Feb 15 01:16:06 EST 1996 jhtp3beans/deitel26.gif4852 Thu Feb 15 01:17:18 EST 1996 jhtp3beans/deitel27.gif4929 Thu Feb 15 01:18:18 EST 1996 jhtp3beans/deitel28.gif4914 Thu Feb 15 01:19:16 EST 1996 jhtp3beans/deitel29.gif4769 Thu Feb 15 00:42:52 EST 1996 jhtp3beans/deitel3.gif4617 Thu Feb 15 00:43:54 EST 1996 jhtp3beans/deitel4.gif4335 Thu Feb 15 00:47:14 EST 1996 jhtp3beans/deitel5.gif3967 Thu Feb 15 00:49:40 EST 1996 jhtp3beans/deitel6.gif3200 Thu Feb 15 00:50:58 EST 1996 jhtp3beans/deitel7.gif3393 Thu Feb 15 00:52:32 EST 1996 jhtp3beans/deitel8.gif4006 Thu Feb 15 00:53:48 EST 1996 jhtp3beans/deitel9.gif 420 Sun Mar 14 11:36:16 EST 1999 jhtp3beans/LogoAnimator$1.class3338 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. extends LogoAnimator

2. setAnimationDelay

3. 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

1212 public void setAnimationDelay( int value )

13 {

14 animationDelay = value;

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();

Methods must follow format.

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 }

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 )

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.tmp1 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

– Use same package

– Subclass of JPanel, can add JSlider and JTextField

3 package jhtp3beans;

12 public class SliderFieldPanel extends JPanel

13 implements Serializable {

Creating a JavaBean with a Bound Property

– Create object• argument (this) - source of PropertyChangeEvent

– Register ChangeListener• When changed, calls setCurrentValue• Notifies registered PropertyChangeListeners

25 changeSupport = new PropertyChangeSupport( this );

40 slider.addChangeListener(

41 new ChangeListener() {

42 public void stateChanged( ChangeEvent e )

43 {

44 setCurrentValue( slider.getValue() );

45 }

46 }

47 );

Creating a JavaBean with a Bound Property

– Help register ChangeListeners• Supply listener interface and event class

• Must have methods for adding/removing listeners

• Use this naming for bound property events

67 public void removePropertyChangeListener(

68 PropertyChangeListener listener )

69 {

70 changeSupport.removePropertyChangeListener( listener );

71 }

61 public void addPropertyChangeListener( 62 PropertyChangeListener listener ) 63 {64 changeSupport.addPropertyChangeListener( listener );65 }66

Creating a JavaBean with a Bound Property

– currentValue - bound property• setCurrentValue, getCurrentValue• When changes, must notify registered PropertyChangeListeners

– Method firePropertyChange( propertyName, oldValue, newValue );

• Of PropertyChangeSupport• Notifies registered listeners

106 public void setCurrentValue( int current )

107 {

112 changeSupport.firePropertyChange(

113 "currentValue", new Integer( oldValue ),

114 new Integer( currentValue ) );

1. package

1.1 extends JPanel

1.2 Declarations

1.3 Constructor

1.4 PropertyChange Support

1.5 GUI

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.*;

6 import javax.swing.event.*;7 import java.io.*;

8 import java.awt.*;

9 import java.awt.event.*;

10 import java.beans.*;

11

12 public class SliderFieldPanel extends JPanel

13 implements Serializable {

14 private JSlider slider;

15 private JTextField field;

16 private Box boxContainer;

17 private int currentValue;18

19 // object to support bound property changes

20 private PropertyChangeSupport changeSupport;

21

22 public SliderFieldPanel()

23 {

24 // create PropertyChangeSupport for bound properties

2525 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 );

Create new object, used to register change listeners.

1.6 Event handlers34 boxContainer.add( Box.createHorizontalStrut( 5 ) );

35 boxContainer.add( field );

36

37 setLayout( new BorderLayout() );

38 add( boxContainer );

39

4040 slider.addChangeListener(

41 new ChangeListener() {

42 public void stateChanged( ChangeEvent e )

43 {

44 setCurrentValue( slider.getValue() );

45 }

46 }

47 );

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

31

32 boxContainer = new Box( BoxLayout.X_AXIS );

33 boxContainer.add( slider );

Call method setCurrentValue when value changes.

2. addPropertyChange Listener

3. removeProperty ChangeListener

67 public void removePropertyChangeListener(

68 PropertyChangeListener listener )

69 {

70 changeSupport.removePropertyChangeListener( listener );

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

60 // methods for adding and removing PropertyChangeListeners6161 public void addPropertyChangeListener( 62 PropertyChangeListener listener ) 63 {64 changeSupport.addPropertyChangeListener( listener );65 }66 Methods to support registration.

Methods must have this naming.

4. setCurrentValue

4.1 firePropertyChange

5. getCurrentValue100 public int getMaximumValue() 101 { 102 return slider.getMaximum(); 103 }104105 // property currentValue106 public void setCurrentValue( int current )107 { 108 int oldValue = currentValue;109 currentValue = current;110 slider.setValue( currentValue );111 field.setText( String.valueOf( currentValue ) );112 changeSupport.firePropertyChange( 113 "currentValue", new Integer( oldValue ), 114 new Integer( currentValue ) );115 } 116117 public int getCurrentValue() 118 {119 return slider.getValue(); 120 }

89 // property maximumValue90 public void setMaximumValue( int max )91 {92 slider.setMaximum( max ); 93 94 if ( slider.getValue() > slider.getMaximum() ) {95 slider.setValue( slider.getMaximum() );96 field.setText( String.valueOf( slider.getValue() ) );97 }98 }99

Pass name, old value, and new value. This notifies registered listeners of change.

6. set/get methods

133134 public Dimension getMinimumSize()135 {136 return boxContainer.getMinimumSize();137 }138139 public Dimension getPreferredSize()140 {141 return boxContainer.getPreferredSize();142 }143}

121122 // property fieldWidth123 public void setFieldWidth( int cols ) 124 { 125 field.setColumns( cols );126 boxContainer.validate();127 }128129 public int getFieldWidth() 130 { 131 return field.getColumns(); 132 }

Creating a JavaBean with a Bound Property

• Create bean– Compile: javac -d . SliderFieldPanel.java– Manifest file (manifest.tmp)

• No Main-Class: because not an application

– Archive in JAR file: jar cfm SliderFieldPanel.jar manifest.tmp jhtp3beans\*.*

1 Name: jhtp3beans/SliderFieldPanel.class

2 Java-Bean: True

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

– SimpleBeanInfo• Default implementation of BeanInfo• Selectively override methods

– 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

7 public class SliderFieldPanelBeanInfo extends SimpleBeanInfo {

8 public final static Class beanClass =

9 SliderFieldPanel.class;

Specifying the BeanInfo Class for a JavaBean

– getPropertyDescriptors (overridden)• Returns array of PropertyDescriptor objects

– Each describes property– new PropertyDescriptor( "propertyName", beanClass )

• Property must have named set and get methods

– setBound( true )• Specifies property is bound

14 PropertyDescriptor fieldWidth =

15 new PropertyDescriptor( "fieldWidth", beanClass );

12 {11 public PropertyDescriptor[] getPropertyDescriptors()

26 currentValue.setBound( true );

Specifying the BeanInfo Class for a JavaBean

– getDefaultPropertyIndex (overridden)• Returns array index of default property

• In this case, currentValue

– getEventSetDescriptors• Returns array of EventSetDescriptor objects

• Describes events supported by bean

39 public int getDefaultPropertyIndex()

40 {

41 return 1;

42 }

44 public EventSetDescriptor[] getEventSetDescriptors() {

Specifying the BeanInfo Class for a JavaBean

– 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

46 EventSetDescriptor changed =

47 new EventSetDescriptor( beanClass,

48 "propertyChange",

49 java.beans.PropertyChangeListener.class,

50 "propertyChange");

Specifying the BeanInfo Class for a JavaBean

– Class EventSetDescriptor– Method setDisplayName( stringName )

• Specifies name for event set in builder tool

52 changed.setDisplayName(

53 "SliderFieldPanel value changed" );

1. package

1.1 import

1.2 extends SimpleBeanInfo

1.3 Class

2. getProperty Descriptors

2.1 setBound

1 // Fig. 25.38: SliderFieldPanelBeanInfo.java

2 // The BeanInfo class for SliderFieldPanel

33 package jhtp3beans;

4

5 import java.beans.*;

6

77 public class SliderFieldPanelBeanInfo extends SimpleBeanInfo {

88 public final static Class beanClass =

9 SliderFieldPanel.class;

10

11 public PropertyDescriptor[] getPropertyDescriptors()

12 {

13 try {

1414 PropertyDescriptor fieldWidth =

15 new PropertyDescriptor( "fieldWidth", beanClass );

16 PropertyDescriptor currentValue =

17 new PropertyDescriptor(

18 "currentValue", beanClass );

19 PropertyDescriptor maximumValue =

20 new PropertyDescriptor(

21 "maximumValue", beanClass );

22 PropertyDescriptor minimumValue =

23 new PropertyDescriptor( "minimumValue", beanClass );

24

25 // ensure PropertyChangeEvent occurs for this property

2626 currentValue.setBound( true );

27

Extend SimpleBeanInfo class, with default implementation of BeanInfo interface.

Create Class object, provides access to class definition.

Same package as bean.

Specify properties that can be exposed by builder.

Specify bound property.

3. getDefaultProperty Index

4. getEventSet Descriptors

4.1 Constructor

4.2 setDisplayName

34 throw new RuntimeException( ie.toString() );

35 }

36 }

37

38 // the index for the currentValue property

3939 public int getDefaultPropertyIndex()

40 {

41 return 1;

42 }

43

44 public EventSetDescriptor[] getEventSetDescriptors() {

45 try {

4646 EventSetDescriptor changed =

47 new EventSetDescriptor( beanClass,

48 "propertyChange",

49 java.beans.PropertyChangeListener.class,

50 "propertyChange");

51

5252 changed.setDisplayName(

53 "SliderFieldPanel value changed" );

54

55 EventSetDescriptor[] descriptors = { changed };

28 PropertyDescriptor descriptors[] = { fieldWidth,29 currentValue, maximumValue, minimumValue };3031 return descriptors;32 }33 catch ( IntrospectionException ie ) {

Get array index of default property (currentValue).

Describes events supported by bean.

Set title of event in builder.

Program Output

56

57 return descriptors;

58 }

59 catch (IntrospectionException e) {

60 throw new RuntimeException(e.toString());

61 }

62 }

63 }

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