Docstoc

JavaBeans

Document Sample
JavaBeans Powered By Docstoc
					              Brown Bag Discussion – Java Beans
                Wednesday, February 20, 2002
Sun Bean Box

Sun created a Bean Box to inspect beans. It is simple to use and is very useful. The
problem is that a bean is also a class in Java. However, there are a few additional
requirements that must be met. The Bean Box will not work with the bean if the
requirements are not met. Thus we have a quick way to verify a bean is a bean.

Duke ™ is very import to Sun as this particular logo represents the break through of the
Java Bean. Duke represents what a Bean can do. It is fun to run it in the Bean Box.

My Adder Bean is very simple, but it works complexly in the Bean Box. It shows how a
Bean is just a class that obeys some simple rules. Here is the code for the Adder Bean in
its entirety in Figure 1. All comments have been removed for brevity.

   package adderdemo;
   import java.awt.*;
   public class Adder extends Panel
   {
       private double a;
       private double b;
       private TextField myTextField = new TextField(8);
       public Adder()
       {
           setLayout(new BorderLayout());
           add(myTextField, BorderLayout.CENTER);
       }
       public double add(){return a + b;}
       public double getA(){return a;}
       public double getB(){return b;}
       public void setA(double newA)
       {
           a = newA;
           myTextField.setText(Double.toString(add()));
       }
       public void setB(double newB)
       {
           b = newB;
           myTextField.setText(Double.toString(add()));
       }
   }
               Figure 1 – Adder Bean



Note the Adder Bean is very short. All it does is reflect the values of its properties (a and
b) in a Text Field. What it interesting is that the GUI Text Field is itself a Bean. Its most
distinguishing feature is that the mutators (setters) refresh the Text Field with the latest
sum by invoking the method “add ”.



8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf          2/15/11
1 of 10
               Brown Bag Discussion – Java Beans
                 Wednesday, February 20, 2002
What are Beans?

As stated in the power point slides, they are a class with several additional requirements.
Actually most of these requirements are met if one follows good programming standards.
The requirements are:

   1.   All attributes must be decaled as private.
   2.   All visible attributes must have accessor and mutators.
   3.   A zero parameter constructor must be present.
   4.   Must be serializable or inherit from a serialzable class. (Note in our Adder Bean
        it inherited from a Canvas which is serializable).
   5.   Must be stored in a jar.
   6.   The jar must have a manifest file with the file extension “mf”.
   7.   The manifest file must have an entry that states that the class is a Bean. For
        example the manifest file for the Adder Bean is in Figure 2.
   8.   If it is to be used in an IDE Pallete, it must have an Info file. All Ide‟s generate
        this file for you. For an example Info file see Figure 3.
   9.   Most importantly, A Bean is invoked differently. It is not instantiated with
        “new”. Instead it is invoked with a class loader. First it looks for an object. If
        such an object is not found, it then looks for a class. The class loader may be
        customized to allow for Beans to be located anywhere, even remotely.


            Manifest-Version: 1.0
            Name: adderdemo/Adder.class
            Java-Bean: True

                    Figure 2- manifest.mf


To build the jar it is useful to use Sun‟s jar tool that comes with the Java Development
Kit. Such jar builders as the one in IBM Visual Age has not proved useful to me. I seem
to have a problem of getting to set the Java-Bean to True. It wants to make this
parameter false in all cases. To build a jar in the DOS window, one just keys in the
flowing DOS command:

        jar cfm adderdemo.jar adderdemo\*.mf adderdemo\*.class

All the files must be in the folder called “adderdemo.” „c‟ stands for create, „f‟ for
archive file name follows, and „m‟ means the manifest file is second. As it turns out as
with the Java complier, no output means it ran successfully.

All of these requirements do not really tell what a Bean really is. A Java Bean is a
reusable software component. The behaviors all are public so that other beans and Java
classes can see its public interface. Its interface consists of its accessor and mutators to

8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf          2/15/11
2 of 10
              Brown Bag Discussion – Java Beans
                Wednesday, February 20, 2002
make its attributes public, its public behavior, and any required behaviors that support its
ability to communicate events. It also may be persistent.


package adderbean;
import java.beans.*;
import java.awt.event.*;
import java.lang.reflect.*;
public class AdderBeanInfo extends SimpleBeanInfo
{
     public EventSetDescriptor[] getEventSetDescriptors()
     {
          EventSetDescriptor aDescriptorList[] = {};
          return aDescriptorList;
     }
     public MethodDescriptor[] getMethodDescriptors()
     {
          MethodDescriptor aDescriptorList[] = {};
          return aDescriptorList;
     }
     public PropertyDescriptor[] getPropertyDescriptors()
     {
          try
          {
               Class class = adderdemo.Adder.class;
               PropertyDescriptor pd1 =
                     new PropertyDescriptor ("a", class);
               PropertyDescriptor pd2 =
                     new PropertyDescriptor ("b", class);
               PropertyDescriptor aDescriptorList[]
                     = {pd1, pd2};
               return aDescriptorList;
          }
          catch (Throwable exception){}
          return null;
     }
}
     Figure 3 – Info Class for Adder Bean




Why use Beans

As stated in the power point slides, here is where Microsoft is ahead of Sun. Visual
Basic programmers are very productive. This is because they simple drop Controls on a

8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf          2/15/11
3 of 10
               Brown Bag Discussion – Java Beans
                 Wednesday, February 20, 2002
palette to create a user interface. The original idea behind Java Beans was to do just that.
All advanced IDEs Sun‟s Forte, IBM‟s Visual Age, Borland‟s JBuilder, and Webgain‟s
Visual Café utilize Java Beans in this way. I have chosen to not use this feature in Cal
Poly‟s programming classes. It allows essentially a graphical way to program by
connecting the Beans together visually. The problem with this approach it does not
appear to be adopted by the Java mainstream. Also the IDEs all differ in how they
approach this. However, creating Java Beans is an industry. All of the Java Swing
components are Java Beans. Web sites exist that sell or make available Beans for low
cost. See: http://www.gamelan.com/

A real nice Bean comes from Kai Todter. It is a great Calendar Bean that I plan to use in
my upcoming CIS 424 classes. To download both the jar and the source code see:
http://www.toedter.com/en/jcalendar.html
I also have these files on my web site for this Brown Bag session. Also I have a unique
test program that shows how to use its features to set the date for such purposes as birth
dates and expected car rental return dates. See “TestCalendar.java”

Finally one must remember, the real feature is the componentry part of a Bean. It is
invoked in such a way that allows for libraries of components to be used. It is this feature
that promises the most potential.

Three ways a Bean Communicates

This section is the most critical if one is to really teach how to build Beans. One must
know how to communicate with Beans. Most books just show how to send a message
top a Bean. Others may show how to bind properties, But very few show how to listen
for a Bean‟s events. This entails creating ones own classes for events and understanding
the publish and subscribe patterns.

Message Bean

A message Bean is the simplest bean. It is able to publish its behaviors to the outside
world. That way other classes may send messages to it. I have developed a simple
example to illustrate all three types of Java Beans. The example is in all three cases
consists of a panel called “PainterPanel” that is painted a color by another Bean that
communicates to it. The other Bean called “SelectorPanel” and it allows a user to select
a color. It then sends a message to the Painter Panel each time the color changes. The
Painter Panel Bean has three areas. One is a label, the second is the selector bars, and the
last is the text fields that contain the values of the scroll bars. The purpose of each scroll
bar is to select a color. The three scroll bars control the Red, Green, and Blue values.
The first example is simple.

Figure 4 shows the Painter Panel and its message “changeColor.” Figure 5 shows the
essence of the Selector Panel without its constructor. Figure 6 shows the constructor.
The point is that the Beans look like any other classes in this case. What is different is

8aa8ea57-b995-4b06-9942-d744786682f5.doc             by Professor Stumpf          2/15/11
4 of 10
             Brown Bag Discussion – Java Beans
               Wednesday, February 20, 2002
how the Beans are called. Figure 7 shows how to invoke and connect the two beans.

              package colorbeanmessage;
              import java.awt.*;
              import javax.swing.*;
              import java.beans.*;
              public class PainterPanel extends JPanel
              {
                    public PainterPanel()
                    {
                          setBackground(Color.white);
                    }
                    public void changeColor(Color color)
                    {
                          this.setBackground(color);
                    }
              }
              Figure 4 – Painter Panel publishing a Message




        package colorbeanmessage;
        import java.awt.*;
        import java.awt.event.*;
        import java.beans.*;
        import java.util.*;
        import javax.swing.*;
        import javax.swing.event.*;
        public class SelectorPanel extends javax.swing.JPanel
        {
            // instance variable
            private Color color = new Color(255, 255, 255);
            private PainterPanel painterPanel = null;
            // GUIs
            private JSlider redSlider = new JSlider(0, 255, 255);
            private JSlider greenSlider = new JSlider(0, 255, 255);
            private JSlider blueSlider = new JSlider(0, 255, 255);
            private JLabel redLabel = new JLabel("Red", JLabel.LEFT);
            private JLabel greenLabel = new JLabel("Green", JLabel.LEFT);
            private JLabel blueLabel = new JLabel("Blue", JLabel.LEFT);
            private JTextField redTextField = new JTextField("255", 8);
            private JTextField greenTextField = new JTextField("255", 8);
            private JTextField blueTextField = new JTextField("255", 8);
            private JPanel labelPanel = new JPanel(new GridLayout(3, 1));
            private JPanel sliderPanel = new JPanel(new GridLayout(3, 1));
            private JPanel textFieldPanel=new JPanel(new GridLayout(3, 1));
        }

        Figure 5 – Selector Panel sending a Message




8aa8ea57-b995-4b06-9942-d744786682f5.doc        by Professor Stumpf        2/15/11
5 of 10
            Brown Bag Discussion – Java Beans
              Wednesday, February 20, 2002
  public SelectorPanel()
  {
      setLayout(new BorderLayout());
      labelPanel.add(redLabel);
      labelPanel.add(greenLabel);
      labelPanel.add(blueLabel);
      add(labelPanel, BorderLayout.WEST);
      sliderPanel.add(redSlider);
      sliderPanel.add(greenSlider);
      sliderPanel.add(blueSlider);
      add(sliderPanel, BorderLayout.CENTER);
      textFieldPanel.add(redTextField);
      textFieldPanel.add(greenTextField);
      textFieldPanel.add(blueTextField);
      add(textFieldPanel, BorderLayout.EAST);
      redSlider.addChangeListener(new ChangeListener()
      {
          public void stateChanged(ChangeEvent changeEvent)
          {
              color = new Color(redSlider.getValue(), color.getGreen(),
                             color.getBlue());
              redTextField.setText(Integer.toString(color.getRed()));
              painterPanel.changeColor(color);
          }
      });
      greenSlider.addChangeListener(new ChangeListener()
      {
          public void stateChanged(ChangeEvent changeEvent)
          {
              color = new Color(color.getRed(), greenSlider.getValue(),
                             color.getBlue());
              greenTextField.setText(Integer.toString(color.getGreen()));
              painterPanel.changeColor(color);
          }
      });
      blueSlider.addChangeListener(new ChangeListener()
      {
          public void stateChanged(ChangeEvent changeEvent)
          {
              color = new Color(color.getRed(), color.getGreen(),
                             blueSlider.getValue());
              blueTextField.setText(Integer.toString(color.getBlue()));
              painterPanel.changeColor(color);
          }
      });
  }


  Figure 6 – Selector Panel Constructor




painterPanel = (PainterPanel) Beans.instantiate(null, colorbeanmessage.PainterPanel");
selectorPanel=(SelectorPanel) Beans.instantiate(null, colorbeanmessage.SelectorPanel");
selectorPanel.setPainterPanel(painterPanel);

Figure 7 – instantiating and connecting the Beans



8aa8ea57-b995-4b06-9942-d744786682f5.doc    by Professor Stumpf      2/15/11
6 of 10
              Brown Bag Discussion – Java Beans
                Wednesday, February 20, 2002

Property Bean

A property Bean is a very attractive way to connect beans. What is done is having the
same attribute in each class. Then if one attribute changes, the other one will reflect that
change automatically. From an execution point this is a desirable approach. The first
major change is in the Painter Panel. It must implement the “PropertyChangeListener.”
Then the method “propertyChange” must be implemented and it will change the color.
See Figure 8 for an example of this code.


     public void propertyChange(PropertyChangeEvent propertyChangeEvent)
     {
         // This is run when some other Bean fires this event
         Color myColor = (Color) propertyChangeEvent.getNewValue();
         this.setColor(myColor);
     }

                Figure 8 – propertyChange method for Painter Panel



Now, of course, we must fire this event in another Bean. Three things must be done.
One is to write the add proterty change listener and remove peroperty change listenser
and then fire the event. See Figure 9 for this code.

 public void addPropertyChangeListener(PropertyChangeListener
               propertyChangeListener)
 {
     propertyChangeSupport.addPropertyChangeListener(propertyChangeListener);
 }
 public java.awt.Color getColor()
 {
     return color;
 }
 public void removePropertyChangeListener(PropertyChangeListener
               propertyChangeListener)
 {
     propertyChangeSupport.addPropertyChangeListener(propertyChangeListener);
 }
 public void setColor(java.awt.Color newColor)
 {
     // Set
     Color oldColor = this.color;
     this.color = newColor;
     // Fire notice attribute changed (key instruction)
     propertyChangeSupport.firePropertyChange("color", oldColor, newColor);
 }

            Figure 9 – additions to Selector Panel


8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf          2/15/11
7 of 10
              Brown Bag Discussion – Java Beans
                Wednesday, February 20, 2002

Event Bean

An Event Bean is an import way to connect Beans. It requires both a customer event and
a customer Listener classes. The event class is shown in Figure 10. The key instruction
is the storing of the color when the event is instantiated. Note it extends EventObject.

    package colorbeanevent;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class ColorEvent extends EventObject
    {
        private Color color;
        public ColorEvent(Object source, Color color)
        {
            super(source);
            this.color = color; // Key Instruction
        }
        public Color getColor(){return color;}
    }

                    Figure 10 – Color Event Class


Then there also must be a customer listener class. Note it extends EventListener. It is
shown in Figure 11.

    package colorbeanevent;
    import java.util.*;
    public interface ColorListener extends EventListener
    {
        public void changeColor(ColorEvent colorEvent);
    }

                    Figure 11 – Event Listener Class




Painter Panel then must implement ColorListener. The required method is then
“changeColor” which sets the background to the new color in the Panel. Selector Panel
has three sliders. Each slider listener invokes the method:

       fireColorEvent(new ColorEvent(this, color));

The last part is to write the method “fireColorEvent .” This method is shown in Figure
12. This uses the observer subscriber pattern. What is happening here is the notification
of all the listeners that an event has occurred. This is possibly the most complicated
technique, but it illustrates many concepts for the student. Until this point, they will not

8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf          2/15/11
8 of 10
               Brown Bag Discussion – Java Beans
                 Wednesday, February 20, 2002
 have really grasped events and listeners. For this reason alone, this technique is
 important for advanced students.

   private void fireColorEvent(ColorEvent colorEvent)
    {
        Iterator listenerIterator;
        synchronized (listeners)
        {
            listenerIterator = new ArrayList(listeners).iterator();
        }
        while (listenerIterator.hasNext())
            {
            ColorListener colorListener = (ColorListener)
listenerIterator.next();
            colorListener.changeColor(colorEvent);
        }
    }

                      Figure 12 – Fire Color Event Method



 What is basically done is using the same attribute in each class. Then if one attribute
 changes, the other one will reflect that change automatically. From an execution point
 this is a desirable approach.

 Bean Persistence

 The Adder Bean Test Class has the logic to save the instance when the window closes. It
 creates a serial file (extension “ser”). Then the class loader will read the
 “adderbean/Adder.ser” file and the instance values are restored. The logic to created the
 persistence is shown in Figure 13.

      FileOutputStream file = new FileOutputStream("adderbean/Adder.ser");
      ObjectOutputStream stream = new ObjectOutputStream(file);
      stream.writeObject(myAdder);
      stream.flush();
      stream.close();


 Summary

 Beans are an excellent way to build a component library. The feature of using a Bean in
 a GUI environment is no longer the primary purpose of a Bean. I find that many authors
 missed this point including our own CIS 424 book by Cay Horstmann.

 The best book that gets it right is by Herb Schildt, Java Beans Programming published
 by Osborne / McGraw Hill.


 8aa8ea57-b995-4b06-9942-d744786682f5.doc            by Professor Stumpf         2/15/11
 9 of 10
              Brown Bag Discussion – Java Beans
                Wednesday, February 20, 2002
Thank you very much for your support.

For a copy of all materials and source code information see:

       http://www.csupomona.edu/~rvstumpf/beanproject/beanproject.html

Bob Stumpf

Comments: rvstumpf@csupomona.edu




8aa8ea57-b995-4b06-9942-d744786682f5.doc           by Professor Stumpf   2/15/11
10 of 10

				
DOCUMENT INFO