Wednesday 29 March 2017

The Java Beans API & Using Bean Builder - Java Tutorials

The Java Beans API

The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package. This section provides a brief overview of its contents. Below lists the interfaces in java.beans and provides a brief description of their functionality.


The Interfaces Defined in java.beans

AppletInitializer:  Methods in this interface are used to initialize Beans that are also applets.

BeanInfo:  This interface allows a designer to specify information about the properties, events, and methods of a Bean.

Customizer:  This interface allows a designer to provide a graphical user interface through which a Bean may be configured.

DesignMode:  Methods in this interface determine if a Bean is executing in design mode.

ExceptionListener:  A method in this interface is invoked when an exception has occurred. (Added by Java 2, version 1.4.)

PropertyChangeListener:  A method in this interface is invoked when a bound property is changed.

PropertyEditor:  Objects that implement this interface allow designers to change and display property values.

VetoableChangeListener:  A method in this interface is invoked when a constrained property is changed.

Visibility:  Methods in this interface allow a Bean to execute in environments where a graphical user interface is not available.


The Classes Defined in java.beans

BeanDescriptor:  This class provides information about a Bean. It also allows you to associate a customizer with a Bean.

Beans:  This class is used to obtain information about a Bean.

DefaultPersistenceDelegate:  A concrete subclass of PersistenceDelegate. (Added by Java 2, version 1.4.)

Encoder:  Encodes the state of a set of Beans. Can be used to write this information to a stream. (Added by Java 2, version 1.4.)

EventHandler:  Supports dynamic event listener creation. (Added by Java 2, version 1.4.)

EventSetDescriptor:  Instances of this class describe an event that can be generated by a Bean.

Expression:  Encapsulates a call to a method that returns a result. (Added by Java 2, version 1.4.)

FeatureDescriptor:  This is the superclass of the PropertyDescriptor, EventSetDescriptor, and MethodDescriptor classes.

IndexedPropertyDescriptor:  Instances of this class describe an indexed property of a Bean.

IntrospectionException:  An exception of this type is generated if a problem occurs when analyzing a Bean.

Introspector:  This class analyzes a Bean and constructs a BeanInfo object that describes the component.

MethodDescriptor:  Instances of this class describe a method of a Bean.

ParameterDescriptor:  Instances of this class describe a method parameter.

PersistenceDelegate:  Handles the state information of an object. (Added by Java 2, version 1.4.)

PropertyChangeEvent:  This event is generated when bound or constrained properties are changed. It is sent to objects that registered an interest in these events and implement either the PropertyChangeListener or VetoableChangeListener interfaces.

PropertyChangeListenerProxy:  Extends EventListenerProxy and implements PropertyChange Listener. (Added by Java 2, version 1.4.)

PropertyChangeSupport:  Beans that support bound properties can use this class to notify PropertyChangeListener objects.

PropertyDescriptor:  Instances of this class describe a property of a Bean.

PropertyEditorManager:  This class locates a PropertyEditor object for a given type.

PropertyEditorSupport:  This class provides functionality that can be used when writing property editors.

PropertyVetoException:  An exception of this type is generated if a change to a constrained property is vetoed.

SimpleBeanInfo:  This class provides functionality that can be used when writing BeanInfo classes.

Statement:  Encapsulates a call to a method. (Added by Java 2, version 1.4.)

VetoableChangeListenerProxy:  Extends EventListenerProxy and implements VetoableChange Listener. (Added by Java 2, version 1.4.)

VetoableChangeSupport:  Beans that support constrained properties can use this class to notify VetoableChangeListener objects.

XMLDecoder:  Used to read a Bean from an XML document. (Added by Java 2, version 1.4.)

XMLEncoder:  Used to write a Bean to an XML document. (Added by Java 2, version 1.4.)


A complete discussion of these classes and interfaces is beyond the scope of this book. However, the following program illustrates the Introspector, BeanDescriptor, PropertyDescriptor, and EventSetDescriptor classes and the BeanInfo interface. It lists the properties and events of the Colors Bean that was developed earlier in this chapter.

  // Show properties and events.
  package sunw.demo.colors;
  import java.awt.*;
  import java.beans.*;
  public class IntrospectorDemo {
    public static void main(String args[]) {
      try {
        Class c = Class.forName("sunw.demo.colors.Colors");
        BeanInfo beanInfo = Introspector.getBeanInfo(c);
        BeanDescriptor beanDescriptor = 
                       beanInfo.getBeanDescriptor();

        System.out.println("Bean name = " +
                           beanDescriptor.getName());

        System.out.println("Properties:");
        PropertyDescriptor propertyDescriptor[] =
          beanInfo.getPropertyDescriptors();
        for(int i = 0; i < propertyDescriptor.length; i++) {
          System.out.println("\t" + propertyDescriptor[i].
                             getName());
        } 

        System.out.println("Events:");
        EventSetDescriptor eventSetDescriptor[] =
          beanInfo.getEventSetDescriptors();
        for(int i = 0; i < eventSetDescriptor.length; i++) {
          System.out.println("\t" + eventSetDescriptor[i].
                             getName());
        }
      }
      catch(Exception e) {
        System.out.println("Exception caught. " + e);
      }
    }
  }

The output from this program is the following:

  Bean name = Colors
  Properties:
              rectangular
  Events:
              propertyChange
              component
              mouseMotion
              mouse
              hierarchy
              key
              focus
              hierarchyBounds
              inputMethod




Using Bean Builder

As explained at the start of the chapter, the BDK is not compatible with Java 2, version 1.4. Instead, 1.4 users will need to use the new Bean Builder tool for Bean development. At the time of this writing, Bean Builder is available only as a beta release, and its final form and feature set are subject to change. However, because it is the tool that Java 2, version 1.4 users must use to develop Beans, an overview of Bean Builder is presented here. (Subsequent editions of this book will cover Bean Builder in detail after it is a released product.) Keep in mind that the basic Bean information, such as introspection, described earlier, also applies to Beans used by Bean Builder. Bean Builder is available from http://java.sun.com.

Bean Builder is similar to the BeanBox offered by the BDK, except that it is more powerful and sophisticated. Its operation is also similar to the BeanBox except that it is easier to use. Perhaps the most striking feature of Bean Builder is that it supports two separate modes of operation: design and test. In design mode, you construct a Bean-based application, adding the various components, and wiring them together. In test mode, also called run-time mode, the application is executed and all of the components are live. Thus, it is extremely easy to construct and then test your application. Futhermore, you switch between these two modes by checking or clearing a single check box.

The top (main) window holds the current palette set. This includes a default palette from which you can choose various user-interface objects, such as buttons, scroll bars, lists, and menus. These are Swing rather than AWT objects. But no knowledge of Swing is required to follow along with the example developed later in this section.) You can also load other palettes and JAR files. Each component has associated with it a set of properties. You can examine and set these using the Property Inspector window provided by Bean Builder. The third window, called the design window (or, designer for short), is the window in which you will assemble various components into an application.

In general, to build an application, you will select items from a palette and instantiate them on the designer, setting their properties as necessary by using the Property Inspector window. Once you have assembled the components, you will wire them together by dragging a line from one to another. In the process, you will define the input and output methods that will be called, and what action causes them to be called. For example, you might wire a push button to a text field, specifying that when the push button is pressed, the text field will be cleared.


Building a Simple Bean Builder Application

It is really quite easy to build an application using Bean Builder. In this section, we will walk through the construction of a very simple one that contains a label, a slider control, and a scroll bar. When the slider control is moved, the scroll bar is also moved by the same amount, and vice versa. Thus, moving one causes the other to move, too. Once you have completed this walk through, you will be able to easily build other applications on your own.

First, create a new project by selecting New from the File menu. Next, select javax.swing.JFrame in the list at the top of the Property Inspector window. JFrame is the top-level Swing class for the design window. Next, scroll down in the Property Inspector window until you find title. Change the title to “A Bean Builder App”.

Next, we will add a label to the design. Click on the label button in the Swing palette. This instantiates a JLabel object, which is the Swing class for a label. Then, move the mouse to the designer and outline a rectangle near the top of the window. This defines were the text will go. Then, using the Property Inspector window, find the text entry. Change it to “Move slider or scroll bar.”  fter you do this. Now, find the horizontalAlignment field in the Property Inspector and change its value to CENTER. This will center the text within the label.

Next, select a slider from the palette and add it to the designer. Then, add a scroll bar. The slider is an instance of the Swing class JSlider and the scroll bar is an instance of the Swing class JScrollbar. By default, both the slider and the scroll bar have the same range (0 to 100), so the value of one will translate directly to the value of the other. To make your application look like the one in this book.

Now it is time to wire the components together. To do this, you will position the mouse pointer over one of the connection handles, then drag a “wire” from the connection handle on one component to a connection handle on another component. The component at which you start is the source of some event and the component at which you end is the recipient of the event. Each component has four connection handles, and it doesn’t matter which one you choose. Begin by wiring a connection from the slider to the scroll bar.

After you have completed the connection, the Interaction Wizard will appear. It lets you specify how the two components communicate. In this case, you will define what takes place when the slider is moved. On the first page you will select the event method that will be called when the source object (in this case, the slider) changes position. First, select the Event Adapter radio button (if it is not already selected). Then, select change in the Event Sets list. In Event Methods, stateChanged(ChangeEvent) should already be selected. 

Press Next. You will now select the method on the target object (in this case, the scroll bar) that you want called when the source object changes. In this case, select the JScrollbar method setValue(int). It sets the current position of the scroll bar.

Press Next. Now, select the “getter” method that will supply the argument to setValue( ). In this case, it will be JSlider’s getValue( ) method, which returns the current position of the slider. A “getter” is a method that uses the get design pattern. Now, press finish. This completes the connection. Now, each time the slider changes, the setValue( ) method of the scroll bar is called with an argument supplied by the getValue( ) method of the slider. Thus, moving the slider also causes the scroll bar to move.

Next, repeat this process, except this time, wire the connection from the scroll bar to the slider box. Finally, test the application. To do this, uncheck the Design Mode check box. This causes the application to execute. Try moving the slider box. When it moves, the scroll bar automatically moves, too. This is because of the connection that we wired from the slider to the scroll bar. Assuming that you also wired the reverse connection, moving the scroll bar will cause the slider to move.

You can save your application by selecting Save in the file menu. The Bean Builder is a powerful, yet easy to use development tool. If Bean development is in your future, you will want to master its features. The best way to do this is to create a number of sample Bean applications. Also, try creating your own Beans and loading them into the palette. (To do so, create a JAR file containing your Beans, as described earlier.)

No comments:

Post a Comment