1 / 62

JavaBeans

JavaBeans. Definition: What is a Bean?.

sela
Download Presentation

JavaBeans

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaBeans

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

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

  4. 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/

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

  6. Properties customizes selected bean. Method Tracer displays debugging messages (not discussed) ToolBox has 16 sample JavaBeans BeanBox window tests beans. Background currently selected (dashed box). BeanBox Overview • Use screen captures from Windows • Start application, following appears:

  7. BeanBox Overview • Initially, background selected • Customize in Properties box

  8. 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"

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

  10. Properties for juggler. BeanBox Overview • Add another button (same steps) • "Stop the Animation" • Add animation bean • In ToolBox, select Juggler and add to BeanBox • Animation begins immediately

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

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

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

  14. BeanBox Overview • Save as design • Can reloaded into BeanBox later • Can have any file extension • Opening • Applet beans (like Juggler) begin executing immediately

  15. BeanBox Overview • Save as Java Applet • File->Make Applet • Stores .class file in .jar (Java Archive File) • Can rename and change directory

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

  17. 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> HTML file 1. archive

  18. Program Output

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

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

  21. 1 // Fig. 25.22: LogoAnimator.java 2 // Animation bean JavaBean classes are normally packaged. 3package jhtp3beans; Allows persistence, so JavaBean can be written and saved. 4 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.io.*; 8 import java.net.*; 9 import javax.swing.*; 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 } 1. package statement 2. implements Serializable

  22. 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 } 32 33 startAnimation();

  23. 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 }

  24. 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, Program Output

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

  26. 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 • 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)

  27. 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:

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

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

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

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

  32. Adding Beans to the BeanBox • To add to design area • Click bean in ToolBox • Click crosshair where bean should appear

  33. Adding Beans to the BeanBox • Properties window • Shows properties of LogoAnimator • Properties inherited from JPanel

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

  35. 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( DataTypevalue ) publicDataTypegetPropertyName() • Property set and get methods • If using boolean, use isPropertyName() instead of get • We use setAnimationDelay and getAnimationDelay

  36. 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.*; Methods must follow format. 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 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(); 1. extends LogoAnimator 2. setAnimationDelay 3. getAnimationDelay

  37. 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 )

  38. 1 Main-Class: jhtp3beans.LogoAnimator2 2 3 Name: jhtp3beans/LogoAnimator2.class 4 Java-Bean: True 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

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

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

  41. 3 package jhtp3beans; 12 public class SliderFieldPanel extends JPanel 13 implements Serializable { 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

  42. 40 slider.addChangeListener( 41 new ChangeListener() { 42 public void stateChanged( ChangeEvent e ) 43 { 44 setCurrentValue( slider.getValue() ); 45 } 46 } 47 ); 25 changeSupport = new PropertyChangeSupport( this ); Creating a JavaBean with a Bound Property • Create object • argument (this) - source of PropertyChangeEvent • Register ChangeListener • When changed, calls setCurrentValue • Notifies registered PropertyChangeListeners

  43. 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 • Help register ChangeListeners • Supply listener interface and event class • Must have methods for adding/removing listeners • Use this naming for bound property events

  44. 106 public void setCurrentValue( int current ) 107 { 112 changeSupport.firePropertyChange( 113 "currentValue", new Integer( oldValue ), 114 new Integer( currentValue ) ); 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

  45. 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.*; Create new object, used to register change listeners. 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 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 ); 1. package 1.1 extends JPanel 1.2 Declarations 1.3 Constructor 1.4 PropertyChange Support 1.5 GUI

  46. 34 boxContainer.add( Box.createHorizontalStrut( 5 ) ); 35 boxContainer.add( field ); 36 37 setLayout( new BorderLayout() ); 38 add( boxContainer ); 39 Call method setCurrentValue when value changes. 40 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 ); 1.6 Event handlers

  47. 67 public void removePropertyChangeListener( 68 PropertyChangeListener listener ) 69 { Methods to support registration. Methods must have this naming. 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 PropertyChangeListeners 61 public void addPropertyChangeListener( 62 PropertyChangeListener listener ) 63 { 64 changeSupport.addPropertyChangeListener( listener ); 65 } 66 2. addPropertyChange Listener 3. removeProperty ChangeListener

  48. 100 public int getMaximumValue() 101 { 102 return slider.getMaximum(); 103 } 104 105 // property currentValue Pass name, old value, and new value. This notifies registered listeners of change. 106 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 } 116 117 public int getCurrentValue() 118 { 119 return slider.getValue(); 120 } 89 // property maximumValue 90 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 4. setCurrentValue 4.1 firePropertyChange 5. getCurrentValue

  49. 133 134 public Dimension getMinimumSize() 135 { 136 return boxContainer.getMinimumSize(); 137 } 138 139 public Dimension getPreferredSize() 140 { 141 return boxContainer.getPreferredSize(); 142 } 143 } 121 122 // property fieldWidth 123 public void setFieldWidth( int cols ) 124 { 125 field.setColumns( cols ); 126 boxContainer.validate(); 127 } 128 129 public int getFieldWidth() 130 { 131 return field.getColumns(); 132 } 6. set/get methods

  50. 1 Name: jhtp3beans/SliderFieldPanel.class 2 Java-Bean: True 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\*.*

More Related