Beruflich Dokumente
Kultur Dokumente
• 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
• 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:
• Save as design
– Can reloaded into BeanBox later
– Can have any file extension
• Opening
– Applet beans (like Juggler) begin executing immediately
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
– 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
• Properties window
– Shows properties of LogoAnimator
• Properties inherited from JPanel
Connecting Beans with Events in the BeanBox
• 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;
– 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
• Create bean
– Compile: javac -d . SliderFieldPanel.java
– Manifest file (manifest.tmp)
1 Name: jhtp3beans/SliderFieldPanel.class
2 Java-Bean: True
• 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
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
– 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
• 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