You are on page 1of 10

UNIT 7: JAVABEANS COMPONENTS Lecture-31 Topics: (i)Beans (ii) The Bean-Writing Process

(i)Beans: A Bean is a JavaBeans component. Beans are independent, reusable software modules. Beans may be visible objects, like AWT components, or invisible objects, like queues and stacks. A builder/integration tool manipulates Beans to create applets and applications

Beans Architecture Beans consist of three things: Events Properties Methods Also, since Beans rely on their state, they need to be able to be persistent over time. Events Events are for notifying others when something is happening. The delegation-event model of AWT, introduced with Java 1.1, demonstrates the Beans event model. It has three parts: EventObjects AWTEvent in the AWT world. EventListeners ActionListener, ItemListener, ... and Event Sources (Beans) The different AWT Components. Anyone can register an EventListener with a Component, provided the Component understands the event set. (For instance, you cannot register an ActionListener with a TextArea, but you can with a TextField). When something happens within the Component, it notifies any listener(s) by sending each an EventObject, through the appropriate method of the listener.

Properties Properties define the characteristics of the Bean. For instance, when examining an AWT TextField for its properties, you will see properties for the caret position, current text, and the echo character, among others. In the simplest case, a method or methods in the following design pattern defines a property: public void setPropertyName(PropertyType value); public PropertyType getPropertyName();

Where PropertyName is the name of the property, and PropertyType is its datatype. If only one method is present, the property is read-only (set missing) or write-only (get missing). Methods Bean methods are available for anyone to call by just making each public. However, you can restrict which methods are visible to the Bean builder/integration tool by providing a getMethodDescriptors method along with your Bean's BeanInfo. Every Bean can provide a supporting BeanInfo class to customize a Bean's appearance to an integration tool.

(ii)The Bean-Writing Process: First, we want to stress that writing a bean is not technically difficultthere are only a few new classes and interfaces for you to master. In particular, the simplest kind of bean is really nothing more than a Java class that follows some fairly strict naming conventions for its methods. Writing Bean Components To create a Bean, you need to determine what it should do and then define the events, properties, and methods to get it there. Actually, most of the method definitions fall out of the definition of events and properties for the Bean. Events An event allows your Beans to communicate when something interesting happens. There are three parts to this communication: EventObject EventListener - (the sink) An Event Source (the Bean) EventObject The java.util.EventObject class is the basis of all Beans events. public class java.util.EventObject extends Object implements java.io.Serializable { public java.util.EventObject (Object source); public Object getSource(); public String toString(); }

Lecture-32 Topic:Naming Patterns for Bean.

Naming Patterns for Bean:There is a j ava. beans. Beans class, but all methods in it are static. Extending it would, therefore, be rather pointless, even though you will see it done occasionally, supposedly for greater clarity. Clearly, because a bean can't extend both Beans and Component, this approach can't work for visual beans. In fact, the Beans class contains methods that are designed to be called by builder tools, for example, to check whether the tool is operating at design time or run time. Other languages for visual design environments, such as Visual Basic and C#, have special keywords such as Property and Event to express these concepts directly. The designers of the Java specification decided not to add keywords to the language to support visual programming. Therefore, they needed an alternative so that a builder tool could analyze a bean to learn its properties or events. Actually, there are two alternative mechanisms. If the bean writer uses standard naming patterns for properties and events, then the builder tool can use the reflection mechanism to understand what properties and events the bean is supposed to expose. Alternatively, the bean writer can supply a b e a n i n f o r m a t i o n class that tells the builder tool about the properties and events of the bean. We start out using the naming patterns becaus Although the documentation calls these standard naming patterns design patterns, these are really only naming conventions and have nothing to do with the design patterns that are used in objectoriented programming. The naming pattern for properties is simple: Any pair of methods public Type get P r o p e r t y N a m e() public void set P r o p e r t y N a m e( T y p e newValue) corresponds to a read/write property. For example, in our ImageViewerBean, there is only one read/write property (for the file name to be viewed), with the following methods: public String getFileName() public void setFileName(String newValue)

If you have a get method but not an associated set method, you define a read-only property. Conversely, a set method without an associated get method defines a write-only property. The get and set methods you create can do more than simply get and set a private data field. Like any Java method, they can carry out arbitrary actions. For example, the setFileName method of the ImageViewerBean class not only sets the value of the fileName data field, but also opens the file and loads the image.

There is one exception to the get/set naming pattern. Properties that have Boolean values should use an is/set naming pattern, as in the following examples: public boolean is P r o p e r t y N a m e( ) public void set P r o p e r t y N a m e(boolean b) For example, an animation might have a property running, with two methods public boolean isRunning() public void setRunning(boolean b) The setRunning method would start and stop the animation. The isRunning method would report its current status. example, when your bean extends JPanel or JLabela large number of uninteresting properties show up in the property inspector. You will see later in this chapter how you can override the automatic property discovery process by supplying b e a n i n f o r m a t i o n. In the bean information, you can specify exactly which properties your bean should expose. For events, the naming patterns are equally simple. A bean builder environment will infer that your bean generates events when you supply methods to add and remove event listeners. All event class names must end in Event, and the classes must extend the EventObj ect class. Suppose your bean generates events of type E v e n t N a m eEvent. The listener interface must be called E v e n t N a m eListener, and the methods to add and remove a listener must be called . public void add E v e n t N a m eListener( E v e n t N a m eListener e) public void remove E v e n t N a m eListener( E v e n t N a m eListener e) If you look at the code for ImageViewerBean, you'll see that it has no events to expose. However, many Swing components generate events, and they follow this pattern. For example, the AbstractButton class generates ActionEvent objects, and it has the following methods to manage ActionListener objects: public void addActionListener(ActionListener e) public void removeActionListener(ActionListener e)

Lecture-33 Topics: (i)Using Beans to Build an Application (ii) Components (i)Using Beans to bulid an Application: To make any bean usable in a builder tool, package into a JAR file all class files that are used by the bean code. Unlike the JAR files for an applet that you saw previously, a JAR file for a bean needs a manifest file that specifies which class files in the archive are beans and should be included in the Toolbox. For example, here is the manifest file ImageViewerBean. mf for ImageViewerBean. Manifest-Version: 1. 0 Name: com/horstmann/corej ava/ImageViewerBean. class Java-Bean: True the blank line between the manifest version and bean name. If your bean contains multiple class files, you just mention in the manifest those class files that are beans and that you want to have displayed in the Toolbox. For example, you could place ImageViewerBean and FileNameBean into the same JAR file and use the manifest Manifest-Version: 1. 0 Name: com/horstmann/corej ava/ImageViewerBean. class Java-Bean: True Name: com/horstmann/corej ava/FileNameBean.class Java-Bean: True To make the JAR file, follow these steps: 1 . Edit the manifest file. 2. Gather all needed class files in a directory. 3. Run the jar tool as follows For example, jar cvfm ImageViewerBean. jar ImageViewerBean. mf com/horstmann/corej ava/*. class You can also add other items, such as GIF files for icons, to the JAR file Builder environments have a mechanism for adding new beans, typically by loading JAR files. Here is what you do to import beans into NetBeans.

Compile the ImageViewerBean and FileNameBean classes and package them into JAR files. Then start NetBeans and follow these steps. 1 . Select Tools -> Palette Manager from the menu. 2. Click the Add from JAR button. 3. In the file dialog box, move to the ImageViewerBean directory and select ImageViewerBean. j ar. 4. Now a dialog box pops up that lists all the beans that were found in the JAR file. Select I mageViewerBean. 5. Finally, you are asked into which palette you want to place the beans. Select Beans. (There are other palettes for Swing components, AWT components, and so on.) (ii) Compnent: JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component.

Lecture-34 Topics: (i)Events Bean Property (ii) Tubes Beaninfo

Event Bean Properties A property is a public attribute of the Bean, usually represented by a non-public instance variable. It can be read-write, read-only, or write-only. There are four different types of properties: Simple Indexed Bound Constrained Simple Properties As the name implies, simple properties represent the simplest of the four. To create a property, define a pair of set/get routines. Whatever name used in the pair of routines, becomes the property name (no matter what instance variable name you use). Normally, the instance variable name matches the property name. However, there is nothing that requires this. For instance, to define a property salary for an Employee Bean: float salary; public void setSalary (float newSalary) {

salary = newSalary; } public float getSalary () { return salary; } Indexed Properties An indexed property is for when a single property can hold an array of values. The design pattern for these properties is: public void setPropertyName (PropertyType[] list) public void setPropertyName ( PropertyType element, int position) public PropertyType[] getPropertyName () public PropertyType getPropertyName (int position)

Bound Properties Revisit the Employee Bean, and make salary a bound property. That way, if two people were using an employee Bean (say a manager and a spouse), and one (the manager) changes an employee's salary, the other (the spouse) would like to know about said change. In order for the notification to happen, you need to maintain a watch list for PropertyChangeEvents via the PropertyChangeSupport class. First, you have to create a list of listeners to maintain: private PropertyChangeSupport changes = new PropertyChangeSupport (this); And then, you have to maintain the list: public void addPropertyChangeListener ( PropertyChangeListener p) { changes.addPropertyChangeListener (p); } public void removePropertyChangeListener ( PropertyChangeListener p) { changes.removePropertyChangeListener (p); } Constrained Properties Constrained properties are similar to bound properties. In addition to maintaining a list of PropertyChangeListeners, the Bean maintains a list of VetoableChangeListeners. Then, prior to the Bean changing a property value, it asks the VetoableChangeListeners if its okay. If it isn't, the listener throws a PropertyVetoException, which you declare the set routine to throw.

Changing salary to be a constrained property (so a spouse can veto salary decreases), results in the following additions: private VetoableChangeSupport vetoes = new VetoableChangeSupport (this); public void addVetoableChangeListener ( VetoableChangeListener v) { vetoes.addVetoableChangeListener (v); } public void removeVetoableChangeListener ( VetoableChangeListener v) { vetoes.removeVetoableChangeListener (v); }

(ii)Tubes Beaninfo: A bean implementor who wishes to provide explicit information about their bean may provide a BeanInfo class that implements this BeanInfo interface and provides explicit information about the methods, properties, events, etc, of their bean. A bean implementor doesn't need to provide a complete set of explicit information. You can pick and choose which information you want to provide and the rest will be obtained by automatic analysis using low-level reflection of the bean classes' methods and applying standard design patterns. You get the opportunity to provide lots and lots of different information as part of the various XyZDescriptor classes. But don't panic, you only really need to provide the minimal core information required by the various constructors. The most common reason for supplying a BeanInfo class is to gain control of the bean properties.You construct a PropertyDescriptor for each property by supplying the name of the property and the class of the bean that contains it. PropertyDescriptor descriptor = new PropertyDescriptor("fileName", ImageViewerBean. class) ; Then implement the getPropertyDescriptors method of your BeanInfo class to return an array of all property descriptors. For example, suppose ImageViewerBean wants to hide all properties that it inherits from the JLabel superclass and expose only the fileName property.

Lecture-35 Topic: (i)Classes Property Editors (ii)Cuatomizes

(i)Classes Property Editor: If you add an integer or string property to a bean, then that property is automatically displayed in the bean's property inspector. But what happens if you add a property whose values cannot easily be edited in a text field, for example, a date or a Color? Then, you need to provide a separate component by which the user can specify the property value. Such components are called p r o p e r t y e d i t o r s . For example, a property editor for a date object might be a calendar that lets the user scroll through the months and pick a date. A property editor for a Color object would let the user select the red, green, and blue components of the color. Actually, NetBeans already has a property editor for colors. Also, of course, there are property editors for basic types such as String (a text field) and boolean (a checkbox). These property editors are registered with the p r o p e r t y e d i t o r m a n a g e r . The process for supplying a new property editor is slightly involved. First, you create a bean info class to accompany your bean. Override the getPropertyDescriptors method. That method returns an array of PropertyDescriptor objects. You create one object for each property that should be displayed on a property editor, e v e n t h o s e f o r w h i c h y o u j u s t w antthedefaulteditor. You construct a PropertyDescriptor by supplying the name of the property and the class of the bean that contains it. PropertyDescriptor descriptor = new PropertyDescriptor("titlePosition", ChartBean.class) Then you call the setPropertyEditorClass method of the PropertyDescriptor class. descriptor.setPropertyEditorClass(TitlePositionEditor. class) ; Next, you build an array of descriptors for properties of your bean. For example, the chart bean that we discuss in this section has five properties: ss A Color property, graphColor A String property, title An int property, titlePosition A double[ ] property, values A boolean property, inverse

(ii) Costomiser: A property editor, no matter how sophisticated, is responsible for allowing the user to set one property at a time. Especially if certain properties of a bean relate to each other, it may be more user friendly to give users a way to edit multiple properties at the same time. To enable this feature, you supply a c u s t o m i z e r instead of (or in addition to) multiple property editors.

In the example program for this section, we develop a customizer for the chart bean. The customizer lets you set several properties of the chart bean at once, and it lets you specify a file from which to read the data points for the chart. you need not follow any naming pattern for the customizer class. The builder can locate it by 1 . Finding the associated BeanInfo class; 2. Invoking its getBeanDescriptor method; and 3. Calling the getCustomiz erClass method.

You might also like