Monday 26 November 2012

Advanced Java Programming -- Java Beans

Advanced Java Programming -- Java Beans
Structure
6.1 Introduction
Objectives
6.2 Using the NetBeans GUI Builder
6.3 Writing a Simple Bean
6.4 Properties
6.5 Simple Properties
Self Assessment Questions
6.6 Bound Properties
Self Assessment Questions
6.7 Constrained Properties
Self Assessment Questions
6.8 Indexed Properties
Self Assessment Questions
6.9 Introspection
Self Assessment Questions
6.10 Summary
6.11 Terminal Question
6.1 Introduction
The JavaBeans™ architecture is based on a component model which enables developers to create software units called components. Components are self-contained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. JavaBean components are known as beans.
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 115
A set of APIs describes a component model for a particular language. The JavaBeans API specification describes the core detailed elaboration for the JavaBeans component architecture.
Beans are dynamic in that they can be changed or customized. Through the design mode of a builder tool you can use the Properties window of the bean to customize the bean and then save (persist) your beans using visual manupulation. You can select a bean from the toolbox, drop it into a form, modify its appearance and behavior, define its interaction with other beans, and combine it and other beans into an applet, application, or a new bean.
The following list briefly describes key bean concepts.
Builder tools discover a bean's features (that is, its properties, methods, and events) by a process known as introspection. Beans support introspection in two ways:
By adhering to specific rules, known as design patterns, when naming bean features. The Introspector class examines beans for these design patterns to discover bean features. The Introspector class relies on the core reflection API. The trail The Reflection API is an excellent place to learn about reflection.
By explicitly providing property, method, and event information with a related bean information class. A bean information class implements the BeanInfo interface. A BeanInfo class explicitly lists those bean features that are to be exposed to application builder tools.
Properties are the appearance and behavior characteristics of a bean that can be changed at design time. Builder tools introspect on a bean to discover its properties and expose those properties for manipulation.
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 116
Beans expose properties so they can be customized at design time. Customization is supported in two ways: by using property editors, or by using more sophisticated bean customizers.
Beans use events to communicate with other beans. A bean that is to receive events (a listener bean) registers with the bean that fires the event (a source bean). Builder tools can examine a bean and determine which events that bean can fire (send) and which it can handle (receive).
Persistence enables beans to save and restore their state. After changing a bean's properties, you can save the state of the bean and restore that bean at a later time with the property changes intact. The JavaBeans architecture uses Java Object Serialization to support persistence.
A bean's methods are no different from Java methods, and can be called from other beans or a scripting environment. By default all public methods are exported.
Beans vary in functionality and purpose. You have probably met some of the following beans in your programming practice:
 GUI (graphical user interface)
 Non-visual beans, such as a spelling checker
 Animation applet
 Spreadsheet application
Self Assessment Questions
1. What is Java Beans?
Objectives
In this chapter, you will learn about the:
 How to use NetBeans GUI Builders.
 Properties of Beans.
 Different Beans Properties
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 117
6.2 Using the NetBeans GUI Builder
This lesson explains how to use the NetBeans IDE GUI Builder to work with beans. In preparation for working with the GUI Builder, you should be first familiar with the key NetBeans concepts which are explained in the Using NetBeans IDE Guide .
This lesson guides you through the process of creating a bean pattern in the NetBeans projects, introduces the user interface of the GUI Builder, and explains how to add your bean object to the palette.
Creating a New Project
In the NetBeans IDE, you always work in a project where you store sources and files. To create a new project, perform the following steps:
1. Select New Project from the File menu. You can also click the New Project button in the IDE toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose the Java Application type. Click the Next button.
3. Enter MyBean in the Project Name field and specify the project location. Do not create a Main class here, because later you will create a new Java class in this project.
4. Click the Finish button.
This figure represents the expanded MyBean node in the Projects list.
Fig. 6.2.1
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 118
Creating a New Form
After creating a new project, the next step is to create a form within which the JavaBeans components and other required GUI components, will be placed.
To create a new form, perform the following sequence of actions:
1. In the Projects list, expand the MyBean node, right-click on the  node and choose New|JFrame Form from the pop-up menu.
2. Enter MyForm as the Class Name.
3. Click the Finish button.
The IDE creates the MyForm form and the MyForm class within the MyBean application and opens the MyForm form in the GUI Builder.
This figure represents the Projects list, where the MyForm class is located.
Fig. 6.2.2
The GUI Builder Interface
When the JFrame form is added to your application, the IDE opens the newly-created form in an Editor tab with a toolbar containing the following buttons::
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 119

– Selection Mode enables you to select one or more objects in the Design Area.

– Connection Mode enables you to set a connection between objects by specifying an event.

– Preview Design enables you to preview the form layout.

– Align commands enable you to align selected objects.

– Change Resizability enables you to set up vertical and horizontal resizing.
When the MyForm form opens in the GUI Builder's Design view, three additional windows appear, enabling you to navigate, organize, and edit GUI forms. These windows include the following:
Design Area: The primary window for creating and editing Java GUI forms. Source and Design toggle buttons enable you to switch between view a class's source code and a graphical view of the GUI components. Click on an object to select it in the Design Area. For a multiple selection, hold down the Ctrl key while clicking on objects.
Inspector: Representation of a tree hierarchy of all the components in your application. The Inspector highlights the component in the tree that is currently being edited.
Palette: A customizable list of available components containing groups for Swing, AWT, Borders, and Beans components. This window enables you to create, remove, and rearrange the categories displayed in the palette using the customizer.
Properties Window: A display of the properties of the component currently selected in the GUI Builder, Inspector window, Projects window, or Files window.
If you click the Source button, the IDE displays the application's Java source code in the editor. Sections of code that are automatically generated by the
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 120
GUI Builder are indicated by blue areas. These blue areas are protected from editing in the Source view. You can only edit code appearing in the white areas of the editor when in Source view. When you make your changes in the Design View, the IDE updates the file's sources.
Creating a Bean
To create your own bean object and add it to the palette for the bean group, execute the following procedure:
1. Select the  node in the MyBean project.
2. Choose New|Java Class from the pop-up menu.
3. Specify the name for the new class, for example, MyBean, then press the Finish button.
4. Expand the MyBean.java and MyBean node and select the Bean Patterns node.
5. Right-click on the Bean Patterns node and choose Add|Property from the pop-up menu.
6. Enter YourName in the PropertyName field as shown in the following figure, then press OK:
Fig. 6.2.3
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 121
1. Now you can analyze the automatically generated code. Notice that set and get methods were included:
2. public class MyBean {
3.
4. /** Creates a new instance of MyBean */
5. public MyBean() {
6. }
7.
8. /**
9. * Holds value of property yourName.
10. */
11. private String yourName;
12.
13. /**
14. * Getter for property yourName.
15. * @return Value of property yourName.
16. */
17. public String getYourName() {
18. return this.yourName;
19. }
20.
21. /**
22. * Setter for property yourName.
23. * @param yourName New value of property yourName.
24. */
25. public void setYourName(String yourName) {
26. this.yourName = yourName;
27. }
28.
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 122
29. }
30. Right-click the MyBean node in the MyBean project tree and choose Tools |Add to Palette from the pop-up menu.
31. Select the Beans group in the Palette tree to add your bean.
Now you can switch to the Palette window by choosing Palette from the Windows menu and make sure that the MyBean component was added to the Beans group.
So far you have created a bean, set the YourName property, and added this bean as a component to the palette.
Adding Components to the Form
Now you can use the Free Design of the GUI Builder and add the MyBean component and other standard Swing components to MyForm.
1. Select the MyForm node in the project tree.
2. Drag the JLabel Swing component from the Palette window to the Design Area. Double-click the component and change the text property to "Enter your name:".
3. Drag the JTextField component from the Palette window to the Design Area. Double-click the component and empty the text field.
4. Drag the JButton component from the Palette window to the Design Area. Double-click the component and enter "OK" as the text property.
5. Add another button and enter "Cancel" as its text property.
6. Align components by using the appropriate align commands.
7. Before you drag the MyBean component from the Pallete you must compile your project because the MyBean component is non-visual and cannot be operated as a visual component. When you Drag and Drop the MyBean component it will not appear in the Design Area. However, you can view it in the Inspector window by expanding the Other Components node, as shown in the following figure.
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 123
8. To summarize, in the previous steps you created a project, developed a JFrame form, added a bean object and included it in your project as a non-visual component. Later in this trail you will learn how to change properties for the bean component and handle events by using the NetBeans GUI Builder.
6.3 Writing a Simple Bean
In this section you will learn more about beans by performing the following actions:
 Creating a simple bean
 Compiling the bean
 Generating a Java Archive (JAR) file
 Loading the bean into the GUI Builder of the NetBeans IDE
 Inspecting the bean's properties and events
Your bean will be named SimpleBean. Here are the steps to create it:
1. Write the SimpleBean code: Put it in a file named SimpleBean.java, in the directory of your choice. Here's the code:
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 124
2. import java.awt.Color;
3. import java.beans.XMLDecoder;
4. import javax.swing.JLabel;
5. import java.io.Serializable;
6.
7. public class SimpleBean extends JLabel
8. implements Serializable {
9. public SimpleBean() {
10. setText( "Hello world!" );
11. setOpaque( true );
12. setBackground( Color.RED );
13. setForeground( Color.YELLOW );
14. setVerticalAlignment( CENTER );
15. setHorizontalAlignment( CENTER );
16. }
17. }
18. SimpleBean extends the javax.swing.JLabel graphic component and inherits its properties, which makes the SimpleBean a visual component. SimpleBean also implements the java.io.Serializable interface. Your bean may implement either the Serializable or the Externalizable interface.
19. Create a manifest, the JAR file, and the class file SimpleBean.class: Use the Apache Ant tool to create these files. Apache Ant is a Java-based build tool that enables you to generate XML-based configurations files as follows:
20. 
Advanced Java Programming Unit 6
Sikkim Manipal University Page No. 125
21.
22. 
23.
24. 
25.
26. 
27. 
28.
29. 
30. 
31. 
32. 

33. 34.
35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 126 46. 47. 48. 49. 50. 51. 52. It is recommended to save an XML script in the build.xml file, because Ant recognizes this file name automatically. 53. Load the JAR file: Use the NetBeans IDE GUI Builder to load the jar file as follows: 54. Start NetBeans. 55. From the File menu select "New Project" to create a new application for your bean. You can use "Open Project" to add your bean to an existing application. 56. Create a new application using the New Project Wizard. 57. Select a newly created project in the List of Projects, expand the Source Packages node, and select the Default Package element. 58. Click the right mouse button and select New|JFrameForm from the pop-up menu.  Select the newly created Form node in the Project Tree. A blank form opens in the GUI Builder view of an Editor tab.  Open the Palette Manager for Swing/AWT components by selecting Palette Manager in the Tools menu.  In the Palette Manager window select the beans components in the Palette tree and press the "Add from JAR" button.  Specify a location for your SimpleBean JAR file and follow the Add from JAR Wizard instructions. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 127  Select the Palette and Properties options from the Windows menu.  Expand the beans group in the Palette window. The SimpleBean object appears. Drag the SimpleBean object to the GUI Builder panel. The following figure represents the SimpleBean object loaded in the GUI Builder panel: Inspect Properties and Events: The SimpleBean properties will appear in the Properties window. For example, you can change a background property by selecting another color. To preview your form, use the Preview Design button of the GUI Builder toolbar. To inspect events associated with the SimpleBean object, switch to the Events tab of the Properties window. You will learn more about bean properties and events in the lessons that follow. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 128 6.4 Properties In the following sections you will learn how to implement bean properties. A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of bean properties include color, label, font, font size, and display size. The JavaBeans™ specification defines the following types of bean properties: Simple – A bean property with a single value whose changes are independent of changes in any other property. Indexed – A bean property that supports a range of values instead of a single value. Bound – A bean property for which a change to the property results in a notification being sent to some other bean. Constrained – A bean property for which a change to the property results in validation by another bean. The other bean may reject the change if it is not appropriate. Bean properties can also be classified as follows:  Writable – A bean property that can be changed  Standard  Expert  Preferred  Read Only – A bean property that cannot be changed.  Hidden – A bean property that can be changed. However, these properties are not disclosed with the BeanInfo class BeanBuilder uses this schema to group and represent properties in the Properties window. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 129 Self Assessment Questions 2. What are the different properties of JavaBeans? 6.5 Simple Properties To add simple properties to a bean, add appropriate getXXX and setXXX methods (or isXXX and setXXX methods for a boolean property). The names of these methods follow specific rules called design patterns. These design pattern-based method names allow builder tools such as the NetBeans GUI Builder, to provide the following features:  Discover a bean's properties  Determine the properties' read/write attributes  Determine the properties' types  Locate the appropriate property editor for each property type  Display the properties (usually in the Properties window)  Alter the properties (at design time) Adding a Title Property In previous lessons you learned how to create a simple property by using the NetBeans GUI Builder. The following procedure shows how to create a simple property in detail: 1. Right-click on the Bean Patterns node in the MyBean class hierarchy. 2. Select Add|Property from the pop-up menu. 3. Fill out the New Property Pattern form as shown in the following figure and click OK. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 130 The following code is automatically generated: public class MyBean { /** Creates a new instance of MyBean */ public MyBean() { } /** * Holds value of property title. */ private String title; /** * Getter for property title. * @return Value of property title. */ public String getTitle() { return this.title; Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 131 } /** * Setter for property title. * @param title New value of property title. */ public void setTitle(String title) { this.title = title; } } Now make your bean visual by extending the JComponent class and implement the Serializable interface. Then, add the paintComponent method to represent your bean. import java.awt.Graphics; import java.io.Serializable; import javax.swing.JComponent; /** * Bean with a simple property "title". */ public class MyBean extends JComponent implements Serializable { private String title; public String getTitle() { return this.title; } public void setTitle( String title ) { this.title = title; } Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 132 protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); if ( this.title != null ) g.drawString(this.title, 0, height ); } } Inspecting Properties Select the MyBean component in the Other Components node in the Inspector window. Now you can analyze the title property in the Properties window and change it. To change the title property press the "..." button and enter any string you wish. The following figure represents the title property set to the "The title" value. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 133 The NetBeans GUI Builder enables you to restrict the changing of a property value. To restrict the changing of the title property, right-click the title property in the Bean Patterns node of the MyBean project. Select Properties from the pop-up menu and the Properties window appears. Choose one of the following property access types from the Mode combo box:  Read/Write  Read only  Write only The Read only property has only the get method only, while the Write only property has only the set method only. The Read/Write type property has both of these methods. Self Assessment Questions 3. What do you mean by Simple Property? 6.6 Bound Properties Bound properties support the PropertyChangeListener (in the API reference documentation) class. Sometimes when a Bean property changes, another object might need to be notified of the change, and react to the change. Whenever a bound property changes, notification of the change is sent to interested listeners. The accessor methods for a bound property are defined in the same way as those for simple properties. However, you also need to provide the event listener registration methods forPropertyChangeListener classes and fire a PropertyChangeEvent (in the API reference documentation) event to the PropertyChangeListener objects by calling their propertyChange methods The convenience PropertyChangeSupport (in the API reference documentation) class enables your bean to implement these methods. Your Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 134 bean can inherit changes from the PropertyChangeSupportclass, or use it as an inner class. In order to listen for property changes, an object must be able to add and remove itself from the listener list on the bean containing the bound property. It must also be able to respond to the event notification method that signals a property change. The PropertyChangeEvent class encapsulates property change information, and is sent from the property change event source to each object in the property change listener list with the propertyChange method. Implementing Bound Property Support Within a Bean To implement a bound property in your application, follow these steps: 1. Import the java.beans package. This gives you access to the PropertyChangeSupport class. 2. Instantiate a PropertyChangeSupport object. This object maintains the property change listener list and fires property change events. You can also make your class a PropertyChangeSupport subclass. 3. Implement methods to maintain the property change listener list. Since a PropertyChangeSupport subclass implements these methods, you merely wrap calls to the property-change support object's methods. 4. Modify a property's set method to fire a property change event when the property is changed. Creating a Bound Property To create the title property as a bound property for the MyBean component in the NetBeans GUI Builder, perform the following sequence of operations: 1. Right-click the Bean Patterns node in the MyBean class hierarchy. 2. Select Add|Property from the pop-up menu. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 135 3. Fill the New Property Pattern form as shown on the following figure and click OK. Fig. 6.6.1 Note that the title property and the multicast event source pattern PropertyChangeListener were added to the Bean Patterns structure. You can also modify existing code generated in the previous lesson to convert the title and lines properties to the bound type as follows (where newly added code is shown in bold): import java.awt.Graphics; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import javax.swing.JComponent; /** * Bean with bound properties. */ Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 136 public class MyBean extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; private final PropertyChangeSupport pcs = new PropertyChangeSupport( this ); public String getTitle() { return this.title; } public void setTitle( String title ) { String old = this.title; this.title = title; this.pcs.firePropertyChange( "title", old, title ); } public String[] getLines() { return this.lines.clone(); } public String getLines( int index ) { return this.lines[index]; } public void setLines( String[] lines ) Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 137 { String[] old = this.lines; this.lines = lines; this.pcs.firePropertyChange( "lines", old, lines ); } public void setLines( int index, String line ) { String old = this.lines[index]; this.lines[index] = line; this.pcs.fireIndexedPropertyChange( "lines", index, old, lines ); } public void addPropertyChangeListener( PropertyChangeListener listener ) { this.pcs.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { this.pcs.removePropertyChangeListener( listener ); } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); paintString( g, this.title, height ); if ( this.lines != null ) { Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 138 int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height ); } } Self Assessment Questions 4. What do you mean by bound property? 6.7 Constrained Properties A bean property is constrained if the bean supports the Vetoable ChangeListener(in the API reference documentation) and Property ChangeEvent(in the API reference documentation) classes, and if the set method for this property throws a PropertyVetoException(in the API reference documentation). Constrained properties are more complicated than bound properties because they also support property change listeners which happen to be vetoers. The following operations in the setXXX method for the constrained property must be implemented in this order: 1. Save the old value in case the change is vetoed. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 139 2. Notify listeners of the new proposed value, allowing them to veto the change. 3. If no listener vetoes the change (no exception is thrown), set the property to the new value. The accessor methods for a constrained property are defined in the same way as those for simple properties, with the addition that the setXXX method throws a PropertyVetoException exception. The syntax is as follows: public void setPropertyName(PropertyType pt) throws PropertyVetoException {code} Handling Vetoes If a registered listener vetoes a proposed property change by throwing a PropertyVetoException exception, the source bean with the constrained property is responsible for the following actions:  Catching exceptions.  Reverting to the old value for the property.  Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report the reversion. The VetoableChangeListener class throws a PropertyVetoException and handles the PropertyChangeEvent event fired by the bean with the constrained property.  The VetoableChangeSupport provides the following operations:  Keeping track of VetoableChangeListener objects.  Issuing the vetoableChange method on all registered listeners.  Catching any vetoes (exceptions) thrown by listeners.  Informing all listeners of a veto by calling vetoableChange again, but with the old property value as the proposed "new" value. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 140 Creating a Constrained Property To create a constrained property, set the appropriate option in the New Property Pattern form as shown on the following figure. Fig. 6.7.1 Note that the Multicast Source Event Pattern - vetoableChangeListener was added to the Bean Patterns hierarchy. You can also modify the existing code generated in the previous lesson to make the title and lines properties constrained as follows (where newly added code is shown in bold): import java.io.Serializable; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 141 import java.awt.Graphics; import javax.swing.JComponent; /** * Bean with constrained properties. */ public class MyBean extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; private final PropertyChangeSupport pcs = new PropertyChangeSupport( this ); private final VetoableChangeSupport vcs = new VetoableChangeSupport( this ); public String getTitle() { return this.title; } /** * This method was modified to throw the PropertyVetoException * if some vetoable listeners reject the new title value */ public void setTitle( String title ) throws PropertyVetoException { String old = this.title; this.vcs.fireVetoableChange( "title", old, title ); Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 142 this.title = title; this.pcs.firePropertyChange( "title", old, title ); } public String[] getLines() { return this.lines.clone(); } public String getLines( int index ) { return this.lines[index]; } /** * This method throws the PropertyVetoException * if some vetoable listeners reject the new lines value */ public void setLines( String[] lines ) throws PropertyVetoException { String[] old = this.lines; this.vcs.fireVetoableChange( "lines", old, lines ); this.lines = lines; this.pcs.firePropertyChange( "lines", old, lines ); } public void setLines( int index, String line ) throws PropertyVetoException { String old = this.lines[index]; this.vcs.fireVetoableChange( "lines", old, line ); this.lines[index] = line; Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 143 this.pcs.fireIndexedPropertyChange( "lines", index, old, line ); } public void addPropertyChangeListener( PropertyChangeListener listener ) { this.pcs.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { this.pcs.removePropertyChangeListener( listener ); } /** * Registration of the VetoableChangeListener */ public void addVetoableChangeListener( VetoableChangeListener listener ) { this.vcs.addVetoableChangeListener( listener ); } public void removeVetoableChangeListener( VetoableChangeListener listener ) { this.vcs.removeVetoableChangeListener( listener ); } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 144 paintString( g, this.title, height ); if ( this.lines != null ) { int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height ); } } Self Assessment Questions 5. What do you mean by constrained property ? 6.8 Indexed Properties An indexed property is an array of properties or objects that supports a range of values and enables the accessor to specify an element of a property to read or write. Indexed properties are specified by the following methods: //Methods to access individual values public PropertyElement getPropertyName(int index) public void setPropertyName(int index, PropertyElement element) and //Methods to access the entire indexed property array public PropertyElement[] getPropertyName() public void setPropertyName(PropertyElement element[]) Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 145 Note that the distinction between the get and set methods for indexed properties is subtle. The get method either has an argument that is the array index of the property, or returns an array. The set method either has two arguments, namely an integer array index and the property element object that is being set, or has the entire array as an argument. Creating an Indexed Property To create an indexed property for your MyBean component, right-click the Bean Patterns node and select Add|Indexed Property from the pop-up menu. Set up Non-Index Options as shown in the following figure. Fig. 6.8.1 The code in the Source window will be changed automatically as follows: import java.awt.Graphics; import java.io.Serializable; Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 146 import javax.swing.JComponent; /** * Bean with simple property 'title'. */ public class MyBean extends JComponent implements Serializable { private String title; public String getTitle() { return this.title; } public void setTitle( String title ) { this.title = title; } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); if ( this.title != null ) g.drawString(this.title, 0, height ); } /** * Holds value of property lines. */ private String[] lines; /** Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 147 * Indexed getter for property lines. * @param index Index of the property. * @return Value of the property at index. */ public String getLines(int index) { return this.lines[index]; } /** * Getter for property lines. * @return Value of property lines. */ public String[] getLines() { return this.lines; } /** * Indexed setter for property lines. * @param index Index of the property. * @param lines New value of the property at index. */ public void setLines(int index, String lines) { this.lines[index] = lines; } /** * Setter for property lines. * @param lines New value of property lines. */ public void setLines(String[] lines) { this.lines = lines; } Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 148 } Add the following code to the MyBean.java component to present the user with a list of choices. You can provide and change these choices at design time. (Newly added code is shown in bold.) import java.awt.Graphics; import java.io.Serializable; import javax.swing.JComponent; /** * Bean with a simple property "title" * and an indexed property "lines". */ public class MyBean extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; public String getTitle() { return this.title; } public void setTitle( String title ) { this.title = title; } public String[] getLines() { return this.lines.clone(); } Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 149 public String getLines( int index ) { return this.lines[index]; } public void setLines( String[] lines ) { this.lines = lines; } public void setLines( int index, String line ) { this.lines[index] = line; } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); paintString( g, this.title, height ); if ( this.lines != null ) { int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height ); } } Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 150 The following figure represents the lines property in the Properties window. Fig. 6.8.1 Notice that this property has a null value. To set up an alternative value, press the "..." button. The form shown in the following figure enables you to add ten items for the lines property list. First remove the default null items. Then add custom items to the list by entering each item value into the Item field and pressing the Add button each time. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 151 Fig. 6.8.2 Self Assessment Questions 6. What do you mean by indexed property ? 6.9 Introspection Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties, events, and methods. This process controls the publishing and discovery of bean operations and properties. This lesson explains the purpose of introspection, introduces the Introspection API, and gives an example of introspection code. Purpose of Introspection A growing number of Java object repository sites exist on the Internet in answer to the demand for centralized deployment of applets, classes, and source code in general. Any developer who has spent time hunting through these sites for licensable Java code to incorporate into a program has Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 152 undoubtedly struggled with issues of how to quickly and cleanly integrate code from one particular source into an application. The way in which introspection is implemented provides great advantages, including: 1. Portability – Everything is done in the Java platform, so you can write components once, reuse them everywhere. There are no extra specification files that need to be maintained independently from your component code. There are no platform-specific issues to contend with. Your component is not tied to one component model or one proprietary platform. You get all the advantages of the evolving Java APIs, while maintaining the portability of your components. 2. Reuse – By following the JavaBeans design conventions, implementing the appropriate interfaces, and extending the appropriate classes, you provide your component with reuse potential that possibly exceeds your expectations. Introspection API The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection. The BeanInfo (in the API reference documentation) interface of the java.beans package defines a set of methods that allow bean implementors to provide explicit information about their beans. By specifying BeanInfo for a bean component, a developer can hide methods, specify an icon for the toolbox, provide descriptive names for properties, define which properties are bound properties, and much more. The getBeanInfo(beanName) (in the API reference documentation) of the Introspector (in the API reference documentation) class can be used by builder tools and other automated environments to provide detailed information about a bean. The getBeanInfo method relies on the naming Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 153 conventions for the bean's properties, events, and methods. A call to getBeanInfo results in the introspection process analyzing the bean’s classes and superclasses. The Introspector class provides descriptor classes with information about properties, events, and methods of a bean. Methods of this class locate any descriptor information that has been explicitly supplied by the developer through BeanInfo classes. Then the Introspector class applies the naming conventions to determine what properties the bean has, the events to which it can listen, and those which it can send. The following figure represents a hierarchy of the FeatureDescriptor classes: Fig. 6.9.1 Each class represented in this group describes a particular attribute of the bean. For example, the isBound method of the PropertyDescriptor class indicates whether a PropertyChangeEvent event is fired when the value of this property changes. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 154 Editing Bean Info with the NetBeans BeanInfo Editor To open the BeanInfo dialog box, expand the appropriate class hierarchy to the bean Patterns node. Right-click the bean Patterns node and choose BeanInfo Editor from the pop-up menu. All elements of the selected class that match bean-naming conventions will be displayed at the left in the BeanInfo Editor dialog box as shown in the following figure: Fig. 6.9.2 Select one of the following nodes to view and edit its properties at the right of the dialog box:  BeanInfo  Bean  Properties  Methods  Event Sources Special symbols (green and red) appear next to the subnode to indicate whether an element will be included or excluded from the BeanInfo class. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 155 If the Get From Introspection option is not selected, the node's subnodes are available for inclusion in the BeanInfo class. To include all subnodes, right-click a node and choose Include All. You can also include each element individually by selecting its subnode and setting the Include in BeanInfo property. If the Get From Introspection option is selected, the setting the properties of subnodes has no effect in the generated BeanInfo code. The following attributes are available for the nodes for each bean, property, event sources, and method:  Name – A name of the selected element as it appears in code.  Preferred – An attribute to specify where this property appears in the Inspector window under the Properties node.  Expert – An attribute to specify where this property appears in the Inspector window under the Other Properties node.  Hidden – An attribute to mark an element for tool use only.  Display Name Code – A display name of the property.  Short Description Code – A short description of the property.  Include in BeanInfo – An attribute to include the selected element in the BeanInfo class.  Bound – An attribute to make the bean property bound.  Constrained – An attribute to make the bean property constrained.  Mode – An attribute to set the property's mode and generate getter and setter methods.  Property Editor Class – An attribute to specify a custom class to act as a property editor for the property..  For Event Source nodes, the following Expert properties are available:  Unicast (read-only)  In Default Event Set Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 156 Introspection Sample The following example represents code to perform introspection: import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; public class SimpleBean { private final String name = "SimpleBean"; private int size; public String getName() { return this.name; } public int getSize() { return this.size; } public void setSize( int size ) { this.size = size; } public static void main( String[] args ) throws IntrospectionException { BeanInfo info = Introspector.getBeanInfo( SimpleBean.class ); for ( PropertyDescriptor pd : info.getPropertyDescriptors() ) System.out.println( pd.getName() ); } Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 157 } This example creates a non-visual bean and displays the following properties derived from the BeanInfo object:  class  name  size Note that a class property was not defined in the SimpleBean class. This property was inherited from the Object class. To get properties defined only in the SimpleBean class, use the following form of the getBeanInfo method: Introspector.getBeanInfo( SimpleBean.class, Object.class ); Self Assessment Questions 7. What is the purpose of Introspection ? 6.10 Summary Developing software by using prepacked components in a form of rapid application development. JavaBeans make RAD development more commonplace in Java software Development. We can also observe certain differences between a Bean and any other class. Every Bean requires a Zero argument constructor. This constructor can initialize the values. A bean does not have public member variables. Instead it provides access methods so that its properties may be read and written. A beans also must support for introspection. A bean can operate with other distributed software by using the networking classess. Components developed as JavaBeans can be integrated with software built with other architectures such as CORBA. Advanced Java Programming Unit 6 Sikkim Manipal University Page No. 158 6.11 Terminal Questions 1. What is the difference between JavaBeans and NetBeans? 2. Explain different bean properties with an example? 3. What is the difference between bound property and constraint property? 4. What gdo you mean by Intropction?

No comments:

Post a Comment