Validated by Amaya

INEW 2338, Advanced Java Study Guide:  JavaBeans

Published November 10, 2004
Revised January 9, 2010 for Amaya compatibility
By Richard G. Baldwin

File: Inew2338Sg009.htm


Welcome

The purpose of this series of tutorial lessons is to help you learn the essential topics covered in INEW 2338, Advanced Java.

These lessons provide questions, answers, and explanations designed to help you to understand the essential Java features covered by the Advanced Java course.

The textbook for this course is Advanced Java Internet Applications, Second Edition by Art Gittleman, ISBN 1-57676-096-0.  This study guide is for Chapter 9 in the textbook.

In addition to the textbook, I recommend that you study my extensive collection of online Java tutorial lessons.  Those tutorial lessons are published at http://www.dickbaldwin.com.

For this particular study guide, you should study lessons 500 through 512 plus lessons 766, 1060, and 2100 at the URL given above.


Questions

1.  The following two boxes contain two Java class definitions.  The code in the second box is designed to exercise the class that is defined in the first box.

import java.io.Serializable;
import java.awt.Component;

public class Inew2338_140Bean extends Component
                         implements Serializable{
  Inew2338_140Bean(){//constructor
    System.out.println("Hello World");
  }//end constructor
}//end class Inew2338_140Bean

class Inew2338_140{

  public static void main(String[] args){
    new Inew2338_140Bean();
  }//end main

}//end class Inew2338_140

True or false?  The class definition in the first box above is a legitimate JavaBeans component.

Answer and Explanation

2. The first box below contains a Java class definition that is intended to behave as a JavaBeans component.

The second box below contains a driver program that is intended to exercise and test the bean in the first box.

The third box below shows a screen shot of the GUI output when the program is first started running.  At this point, there is no output in the command-line screen.

import java.awt.event.*;
import java.awt.*;
import java.io.Serializable;

public class Inew2338_142Bean extends Canvas
                         implements Serializable{

  //The following two instance variables are used
  // for properties.
  private Color colorPropValue;
  private boolean boolPropValue = true;

  public Inew2338_142Bean(){//constructor
    colorPropValue = Color.yellow;
    setBackground(colorPropValue);
  }//end constructor

  //This overridden method defines the display
  // size of the bean object.
  public synchronized Dimension
                              getPreferredSize(){
    return new Dimension(50,50);
  }//end getPreferredSize()

  //The following "set" and "is" methods in
  // conjunction with the instance variable
  // boolPropValue constitute a boolean property.
  // For boolean properties, either a "get"
  // method or an "is" method will support the
  // design pattern requirement.
  public synchronized boolean isBoolPropValue(){
    return boolPropValue;
  }//end isBoolPropValue

  public synchronized void setBoolPropValue(
                                   boolean data){
    boolPropValue = data;
  }//end setBoolPropValue

  //The following "set" and "get" methods in
  // conjunction with the instance variable
  // colorPropValue constitute a property of type
  // Color.
  public synchronized void setColor(
                                  Color inColor){
    colorPropValue = inColor;
  }//end setColor()

  public synchronized Color getColor(){
    return colorPropValue;
  }//end getColor

  //The following three methods are exposed
  // as accessible methods.

  public synchronized void applyColorProperty(){
    this.setBackground(colorPropValue);
  }//end applyColorProperty

  public synchronized void makeBlue(){
    this.setBackground(Color.BLUE);
  };//end makeBlue()

  public synchronized void makeRed(){
    this.setBackground(Color.RED);
  };//end makeRed()

  //The following two methods expose the fact
  // that this bean is able to multicast Action
  // events (but the methods are incomplete for
  // brevity).
  public synchronized void addActionListener(
                               ActionListener e){
    //Incomplete.  Need to put some substance
    // here in a real bean.
    System.out.println(
      "addActionListener not fully implemented");
  }//end addActionListener()

  public synchronized void removeActionListener(
                               ActionListener e){
    //Incomplete.  Need to put some substance
    // here in a real bean.
    System.out.println("removeActionListener not"
                         + " fully implemented");
  }//end removeActionListener

}//end class Inew2338_142Bean

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Inew2338_142 extends JFrame{
  final Inew2338_142Bean myBean;

  public static void main(String[] args){
    new Inew2338_142();
  }//end main

  //This is a member class
  class SetColorListener
                       implements ActionListener{
    public void actionPerformed(ActionEvent e){
      myBean.setColor(Color.green);
    }//end actionPerformed()
  }//end class SetColorListener

  //The following member class is used to
  // instantiate a dummy ActionListener object
  // which is passed to the addActionListener()
  // and removeActionListener() methods of the
  // Bean.
  class MyDummyActionListener
                       implements ActionListener{
    public void actionPerformed(ActionEvent e){
    }//end empty actionPerformed() method
  }//end class MyDummyActionListener

  public Inew2338_142(){//constructor
    setTitle("Bean Test");
    getContentPane().setLayout(new FlowLayout());
    myBean = new Inew2338_142Bean();
    //Add the bean to the JFrame
    getContentPane().add(myBean);

    //Instantiate several test buttons
    JButton buttonToSetColorProp = new JButton(
                           "Set color property");
    JButton buttonToApplyColorProp = new JButton(
                         "Apply color property");
    JButton buttonToGetColorProp = new JButton(
                           "Get color property");
    JButton buttonToInvokeRedMethod =
            new JButton("Invoke makeRed Method");
    JButton buttonToInvokeBlueMethod =
           new JButton("Invoke makeBlue Method");
    JButton buttonToAddActionListener =
              new JButton("Add Action Listener");
    JButton buttonToRemoveActionListener =
           new JButton("Remove Action Listener");
    JButton buttonToSetBooleanProp = new JButton(
                         "Set boolean Property");
    JButton buttonToGetBooleanProp = new JButton(
                         "Get boolean Property");

    //Add the test buttons to the frame
    getContentPane().add(buttonToSetColorProp);
    getContentPane().add(buttonToApplyColorProp);
    getContentPane().add(buttonToGetColorProp);
    getContentPane().
                    add(buttonToInvokeRedMethod);
    getContentPane().
                   add(buttonToInvokeBlueMethod);
    getContentPane().
                  add(buttonToAddActionListener);
    getContentPane().
               add(buttonToRemoveActionListener);
    getContentPane().add(buttonToSetBooleanProp);
    getContentPane().add(buttonToGetBooleanProp);

    setSize(190,380);
    setVisible(true);

    //Register action listener objects for all
    // the test buttons. Use a member class for
    // the first button.
    buttonToSetColorProp.addActionListener(
                         new SetColorListener());

    //Use anonymous inner classes for the
    // remaining buttons.
    buttonToApplyColorProp.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.applyColorProperty();
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToGetColorProp.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          System.out.println(
                   myBean.getColor().toString());
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToInvokeRedMethod.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.makeRed();
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToInvokeBlueMethod.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.makeBlue();
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToAddActionListener.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.addActionListener(
                    new MyDummyActionListener());
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToRemoveActionListener.
                               addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.removeActionListener(
                    new MyDummyActionListener());
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToSetBooleanProp.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          myBean.setBoolPropValue(false);
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    buttonToGetBooleanProp.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                                  ActionEvent e){
          System.out.println(
                       myBean.isBoolPropValue());
        }//end actionPerformed()
      }//end ActionListener
    );//end addActionListener

    //Terminate when frame is closed
    this.addWindowListener(
      new WindowAdapter(){
        public void windowClosing(WindowEvent e){
          System.exit(0);//terminate the program
        }//end windowClosing
      }//end WindowAdapter
    );//end addWindowListener

  }//end constructor
}//end class Inew2338_142.java
//=============================================//

Screen shot at startup

True or false?  When each button in the GUI is clicked once in succession, going from top to bottom, the resulting GUI output is as shown in the first box below and the output in the command-line screen matches that shown in the second box below.

java.awt.Color[r=0,g=0,b=255]
addActionListener not fully implemented
removeActionListener not fully implemented
false

Answer and Explanation

3.  The purpose of the program named Inew2338_144 in the following box is to use introspection to get information about the properties, events, and methods of a bean class, and to save that information in an output file named junk.txt.

import java.io.*;
import java.beans.*;
import java.lang.reflect.*;

public class Inew2338_144{
  //Name of bean class file to be analyzed
  static String beanClassName;
  FileWriter fileWriter;
  PrintWriter printWriter;

  //Start the program and get the name of the
  // class file for the bean into the String
  // beanClassName
  public static void main(String args[])
                                throws Exception{
    if(args.length == 1){
      beanClassName = args[0];
    }else{
      beanClassName = "JunkBean";
    }//end else
    new Inew2338_144();
  }//end main

  //Constructor
  public Inew2338_144() throws Exception {
    //Open an output file to store the report in.
    fileWriter = new FileWriter("junk.txt");
    printWriter = new PrintWriter(fileWriter);

    //Create an object of type Class that
    // represents the class of the bean. The
    // static method Introspector.getBeanInfo()
    // requires either one or two objects of type
    // Class as parameters.  The forName()
    // method of the Class class returns such an
    // object, given the name of a class as a
    // String parameter.
    Class beanClassObj = Class.forName(
                                  beanClassName);

    //Given the Class object that represents the
    // bean's class, use the static getBeanInfo()
    // method of the Introspector class to obtain
    // a BeanInfo object containing information
    // about the class of the bean. The second
    // parameter passed to getBeanInfo() prevents
    // introspection from going further up the
    // inheritance hierarchy.
    BeanInfo beanInfo = Introspector.getBeanInfo(
                   beanClassObj,
                   beanClassObj.getSuperclass());
    //This version of the getBeanInfo method
    // returns information for the bean class
    // and all of its superclasses.
    //BeanInfo beanInfo =
    //    Introspector.getBeanInfo(beanClassObj);

    //A BeanDescriptor object provides
    // information about a bean, including its
    // class, its name, etc. Get a BeanDescriptor
    // object and use it to to extract
    // information about the bean.  Store the
    // information in an output file named
    // junk.txt.
    BeanDescriptor beanDescriptor =
                    beanInfo.getBeanDescriptor();
    printWriter.println("Name of bean:  " +
                       beanDescriptor.getName());
    printWriter.println("Class of bean: " +
                  beanDescriptor.getBeanClass());
    printWriter.println();//blank line

    //A PropertyDescriptor object describes one
    // property that a Java Bean exports via a
    // pair of accessor methods. Use the
    // getPropertyDescriptors() method to create
    // an array of PropertyDescriptor objects,
    // one for each exported property.  Use each
    // such object to extract the name and type
    // of the corresponding property along with
    // the name of the get method, and the name
    // of the set method for that property.
    // Store that information in the output file.
    printWriter.println("==== Properties: ====");
    PropertyDescriptor[] propDescriptor =
               beanInfo.getPropertyDescriptors();
    for (int i = 0;i < propDescriptor.length;
                                            i++){
      printWriter.println("Name: " +
                    propDescriptor[i].getName());
      printWriter.println(" Type:       " +
            propDescriptor[i].getPropertyType());
      printWriter.println(" Get method: " +
              propDescriptor[i].getReadMethod());
      printWriter.println(" Set method: " +
             propDescriptor[i].getWriteMethod());
    }//end for-loop
    printWriter.println();

    //An EventSetDescriptor object describes a
    // type of event that a given Java bean
    // fires. Information about the event can
    // be extracted from each such object.
    printWriter.println("==== Events: ====");
    EventSetDescriptor[] eventSetDescriptor =
               beanInfo.getEventSetDescriptors();
    for(int i = 0;i < eventSetDescriptor.length;
                                            i++){
      printWriter.println("Event Name: " +
                eventSetDescriptor[i].getName());
      printWriter.println(" Add Method:    " +
                       eventSetDescriptor[i].
                         getAddListenerMethod());
      printWriter.println(" Remove Method: " +
                    eventSetDescriptor[i].
                      getRemoveListenerMethod());

      //A MethodDescriptor object provides
      // information about a method.
      MethodDescriptor[] methodDescriptor =
                eventSetDescriptor[i].
                  getListenerMethodDescriptors();
      for(int j = 0;j < methodDescriptor.length;
                                            j++){
        printWriter.println(
                      " Event Handler Method: " +
                  methodDescriptor[j].getName());
      }//end for-loop
    }//end for-loop
    printWriter.println();

    //The getMethodDescriptors() method returns
    // an array of MethodDescriptor objects where
    // each object describes one of the methods
    // that a bean exposes for external access
    // from other components.
    printWriter.println(
                   "==== Exposed Methods: ====");
    MethodDescriptor[] methodDescriptor =
                 beanInfo.getMethodDescriptors();
    for (int i = 0;i < methodDescriptor.length;
                                            i++){
      printWriter.println(methodDescriptor[i].
                                      getName());
    }//end for-loop
    printWriter.println();
    printWriter.close();
  }//end constructor
}//end class Inew2338_144

True or false?  When the above program named Inew2338_144 is used to analyze the bean class named  Inew2338_140Bean (presented earlier in this document), the text stored in the output file named junk.txt is as shown in the following box.

Name of bean: Inew2338_140Bean
Class of bean: class Inew2338_140Bean

==== Properties: ====

==== Events: ====

==== Exposed Methods: ====

Answer and Explanation

4.  True or false?  When the program named Inew2338_144 (described earlier) is used to analyze the bean class named Inew2338_142Bean (described earlier), the program lists the following properties as belonging to the bean:

Answer and Explanation

5.  True or false?  When the program named Inew2338_144 (described earlier) is used to analyze the bean class named Inew2338_142Bean (described earlier), the program lists the following property names, types, and accessor methods.  (Note that the program actually lists the complete method signature for each method whereas the following list was reduced to show only the method names for brevity.)

Name: boolPropValue
 Type:       boolean
 Get method: getBoolPropValue()
 Set method: setBoolPropValue(boolean)
Name: color
 Type:       class java.awt.Color
 Get method: getColor()
 Set method: setColor(java.awt.Color)
Name: preferredSize
 Type:       class java.awt.Dimension
 Get method: getPreferredSize()
 Set method: null

Answer and Explanation

6.  The program in the following box named Inew2338_146 is a modified version of the program named Inew2338_144, which was described earlier.

import java.io.*;
import java.beans.*;
import java.lang.reflect.*;

public class Inew2338_146{
  //Name of bean class file to be analyzed
  static String beanClassName;
  FileWriter fileWriter;
  PrintWriter printWriter;

  //Start the program and get the name of the
  // class file for the bean into the String
  // beanClassName
  public static void main(String args[])
                                throws Exception{
    if(args.length == 1){
      beanClassName = args[0];
    }else{
      beanClassName = "JunkBean";
    }//end else
    new Inew2338_146();
  }//end main

  //Constructor
  public Inew2338_146() throws Exception {
    //Open an output file to store the report in.
    fileWriter = new FileWriter("junk.txt");
    printWriter = new PrintWriter(fileWriter);

    //Create an object of type Class that
    // represents the class of the bean. The
    // static method Introspector.getBeanInfo()
    // requires either one or two objects of type
    // Class as parameters.  The forName()
    // method of the Class class returns such an
    // object, given the name of a class as a
    // String parameter.
    Class beanClassObj = Class.forName(
                                  beanClassName);

    //Given the Class object that represents the
    // bean's class, use the static getBeanInfo()
    // method of the Introspector class to obtain
    // a BeanInfo object containing information
    // about the class of the bean. The second
    // parameter passed to getBeanInfo() prevents
    // introspection from going further up the
    // inheritance hierarchy.
    //BeanInfo beanInfo =
    //                  Introspector.getBeanInfo(
    //             beanClassObj,
    //             beanClassObj.getSuperclass());
    //This version of the getBeanInfo method
    // returns information for the bean class
    // and all of its superclasses.
    BeanInfo beanInfo =
        Introspector.getBeanInfo(beanClassObj);

    //A BeanDescriptor object provides
    // information about a bean, including its
    // class, its name, etc. Get a BeanDescriptor
    // object and use it to to extract
    // information about the bean.  Store the
    // information in an output file named
    // junk.txt.
    BeanDescriptor beanDescriptor =
                    beanInfo.getBeanDescriptor();
    printWriter.println("Name of bean:  " +
                       beanDescriptor.getName());
    printWriter.println("Class of bean: " +
                  beanDescriptor.getBeanClass());
    printWriter.println();//blank line

    //A PropertyDescriptor object describes one
    // property that a Java Bean exports via a
    // pair of accessor methods. Use the
    // getPropertyDescriptors() method to create
    // an array of PropertyDescriptor objects,
    // one for each exported property.  Use each
    // such object to extract the name and type
    // of the corresponding property along with
    // the name of the get method, and the name
    // of the set method for that property.
    // Store that information in the output file.
    printWriter.println("==== Properties: ====");
    PropertyDescriptor[] propDescriptor =
               beanInfo.getPropertyDescriptors();
    for (int i = 0;i < propDescriptor.length;
                                            i++){
      printWriter.println("Name: " +
                    propDescriptor[i].getName());
      printWriter.println(" Type:       " +
            propDescriptor[i].getPropertyType());
      printWriter.println(" Get method: " +
              propDescriptor[i].getReadMethod());
      printWriter.println(" Set method: " +
             propDescriptor[i].getWriteMethod());
    }//end for-loop
    printWriter.println();

    //An EventSetDescriptor object describes a
    // type of event that a given Java bean
    // fires. Information about the event can
    // be extracted from each such object.
    printWriter.println("==== Events: ====");
    EventSetDescriptor[] eventSetDescriptor =
               beanInfo.getEventSetDescriptors();
    for(int i = 0;i < eventSetDescriptor.length;
                                            i++){
      printWriter.println("Event Name: " +
                eventSetDescriptor[i].getName());
      printWriter.println(" Add Method:    " +
                       eventSetDescriptor[i].
                         getAddListenerMethod());
      printWriter.println(" Remove Method: " +
                    eventSetDescriptor[i].
                      getRemoveListenerMethod());

      //A MethodDescriptor object provides
      // information about a method.
      MethodDescriptor[] methodDescriptor =
                eventSetDescriptor[i].
                  getListenerMethodDescriptors();
      for(int j = 0;j < methodDescriptor.length;
                                            j++){
        printWriter.println(
                      " Event Handler Method: " +
                  methodDescriptor[j].getName());
      }//end for-loop
    }//end for-loop
    printWriter.println();

    //The getMethodDescriptors() method returns
    // an array of MethodDescriptor objects where
    // each object describes one of the methods
    // that a bean exposes for external access
    // from other components.
    printWriter.println(
                   "==== Exposed Methods: ====");
    MethodDescriptor[] methodDescriptor =
                 beanInfo.getMethodDescriptors();
    for (int i = 0;i < methodDescriptor.length;
                                            i++){
      printWriter.println(methodDescriptor[i].
                                      getName());
    }//end for-loop
    printWriter.println();
    printWriter.close();
  }//end constructor
}//end class Inew2338_146

True or false?  When the program named Inew2338_146 is used to analyze the bean class named Inew2338_142Bean (described earlier), the program lists the following exposed methods:

==== Exposed Methods: ====
addActionListener
applyColorProperty
getColor
getPreferredSize
isBoolPropValue
makeBlue
makeRed
removeActionListener
setBoolPropValue
setColor

Answer and Explanation

7.  The first box below contains a bean class named Inew2338_148Bean, which is an updated version of the previously described bean class named Inew2338_142Bean.

The second box below contains a public class named Inew2338_148BeanBeanInfo, which extends SimpleBeanInfo and contains several references to Inew2338_148Bean.class(The class named SimpleBeanInfo implements BeanInfo.)

import java.awt.event.*;
import java.awt.*;
import java.io.Serializable;

public class Inew2338_148Bean extends Canvas
                         implements Serializable{

  //The following two instance variables are used
  // for properties.
  private Color colorPropValue;
  private boolean boolPropValue = true;

  public Inew2338_148Bean(){//constructor
    colorPropValue = Color.yellow;
    setBackground(colorPropValue);
  }//end constructor

  //This overridden method defines the display
  // size of the bean object.
  public synchronized Dimension
                              getPreferredSize(){
    return new Dimension(50,50);
  }//end getPreferredSize()

  public synchronized boolean isBoolPropValue(){
    return boolPropValue;
  }//end isBoolPropValue

  public synchronized void setBoolPropValue(
                                   boolean data){
    boolPropValue = data;
  }//end setBoolPropValue

  public synchronized void setColor(
                                  Color inColor){
    colorPropValue = inColor;
  }//end setColor()

  public synchronized Color getColor(){
    return colorPropValue;
  }//end getColor

  public synchronized void xsetColor(
                                  Color inColor){
    colorPropValue = inColor;
  }//end xsetColor()

  public synchronized Color xgetColor(){
    return colorPropValue;
  }//end xgetColor

  //The following three methods are exposed
  // as accessible methods.

  public synchronized void applyColorProperty(){
    this.setBackground(colorPropValue);
  }//end applyColorProperty

  public synchronized void makeBlue(){
    this.setBackground(Color.BLUE);
  };//end makeBlue()

  public synchronized void makeRed(){
    this.setBackground(Color.RED);
  };//end makeRed()

  //The following two methods expose the fact
  // that this bean is able to multicast Action
  // events (but the methods are incomplete for
  // brevity).
  public synchronized void addActionListener(
                               ActionListener e){
    //Incomplete.  Need to put some substance
    // here in a real bean.
    System.out.println(
      "addActionListener not fully implemented");
  }//end addActionListener()

  public synchronized void removeActionListener(
                               ActionListener e){
    //Incomplete.  Need to put some substance
    // here in a real bean.
    System.out.println("removeActionListener not"
                         + " fully implemented");
  }//end removeActionListener

}//end class Inew2338_148Bean

import java.beans.*;

public class Inew2338_148BeanBeanInfo
                          extends SimpleBeanInfo{

  //Overridden getPropertyDescriptors method
  public PropertyDescriptor[]
                        getPropertyDescriptors(){
    try{
      PropertyDescriptor pd0 =
                        new PropertyDescriptor(
                          "color",
                          Inew2338_148Bean.class,
                          "xgetColor",
                          "xsetColor");
      PropertyDescriptor pd1 =
                        new PropertyDescriptor(
                          "boolPropValue",
                          Inew2338_148Bean.class,
                          "isBoolPropValue",
                          "setBoolPropValue");
      PropertyDescriptor pd2 =
                        new PropertyDescriptor(
                          "preferredSize",
                          Inew2338_148Bean.class,
                          "getPreferredSize",
                          null);

      PropertyDescriptor[] pda = {pd0,pd1,pd2};
      return pda;
    }catch(IntrospectionException e){
      return null;
    }//end catch
  }//end getPropertyDescriptors()

}//end class Inew2338_148BeanBeanInfo

True or false?  When the program named Inew2338_144 (described earlier) is used to analyze the bean class named Inew2338_148Bean,in conjunction with the class named Inew2338_148BeanBeanInfo, the program lists the following property names, types, and accessor methods.  (Note that the program actually lists the complete method signature for each method whereas the following list was reduced to show only the method names for brevity.)

Name: boolPropValue
 Type:       boolean
 Get method: isBoolPropValue()
 Set method: setBoolPropValue(boolean)
Name: color
 Type:       class java.awt.Color
 Get method: getColor()
 Set method: setColor(java.awt.Color)
Name: preferredSize
 Type:       class java.awt.Dimension
 Get method: getPreferredSize()
 Set method: null

Answer and Explanation

8.  A simple bean class named Inew2338_150Bean is shown in the first box below.

True or false?  When the program named Inew2338_144 (described earlier) is used to analyze the bean class named Inew2338_150Bean,the program output is as shown in the second box below.  (Note that the program actually lists the complete method signature for each property accessor method whereas the following list was reduced to show only the method names, return types, and argument types for brevity.)

import java.awt.*;
import java.io.Serializable;

public class Inew2338_150Bean
                         implements Serializable{
  private int sizeVar;
  private int[] indexedVar;

  public Inew2338_150Bean(){//constructor
    indexedVar = new int[3];
  }//end constructor
  //-------------------------------------------//

  public synchronized void setSize(int inSize){
    sizeVar = inSize;
  }//end setSize()

  public synchronized int getSize(){
    return sizeVar;
  }//end getSize

  //-------------------------------------------//

  //The following two methods satisfy the design
  // pattern for setting and getting the entire
  // array for an indexed property.

  public synchronized int[] getIndexedProp(){
    return indexedVar;
  }//end getIndexedProp

  public synchronized void setIndexedProp(
                                        int a[]){
    indexedVar = a;
  }//end setIndexedProp

}//end class Inew2338_150Bean.java

Name of bean:  Inew2338_150Bean
Class of bean: class Inew2338_150Bean

==== Properties: ====
Name: indexedProp
 Type:       class [I
 Get method: int[] getIndexedProp()
 Set method: void setIndexedProp(int[])
Name: size
 Type:       int
 Get method: int getSize()
 Set method: void setSize(int)

==== Events: ====

==== Exposed Methods: ====
getIndexedProp
getSize
setIndexedProp
setSize

Answer and Explanation

9.  The first box below contains a bean class named Inew2338_152Bean.

The second box below contains a driver program named Inew2338_152, which exercises the bean class named Inew2338_152Bean.

True or false?  Execution of the driver program named Inew2338_152 produces the output shown in the third box below.  (Note that the date and time will be different each time the program is run.)

import java.awt.*;
import java.io.Serializable;
import java.util.*;
import java.beans.*;

public class Inew2338_152Bean
                        implements Serializable{

  protected Color color = Color.RED;
  protected Date date = new Date();

  //The following reference variable is used to
  // access the list maintenance and event
  // firing capabilities of an object
  // instantiated from the PropertyChangeSupport
  // class.
  PropertyChangeSupport helper;

  public Inew2338_152Bean(){//constructor
    helper = new PropertyChangeSupport(this);
  }//end constructor
  //-------------------------------------------//

  public synchronized void setTheColor(
                                  Color inColor){
    Color oldColor = color;
    color = inColor;
    //Notify property listeners of property
    // change
    if(!color.equals(oldColor))
      notifyPropertyChange("theColor",oldColor);
  }//end setTheColor()

  public synchronized Color getTheColor(){
    return color;
  }//end getTheColor
  //-------------------------------------------//

  public synchronized void setTheDate(
                                    Date dateIn){
    Date oldDate = date;
    date = dateIn;
    //Notify property listeners of change
    if(!date.equals(oldDate))
      notifyPropertyChange("theDate",oldDate);
  }//end setTheDate()
  //-------------------------------------------//

  //The following two methods are used to
  // maintain a list of listener objects that
  // request to be notified of changes to the
  // properties or that request to be removed
  // from the list.  Note that these methods
  // accept a reference to the object requesting
  // registration and pass that reference to the
  // list maintenance facility provided by an
  // object of the PropertyChangeSupport class.

  //Add a property change listener object to
  // the list.
  public synchronized void
                 addPropertyChangeListener(
                   PropertyChangeListener lstnr){
    helper.addPropertyChangeListener(lstnr);
  }//end addPropertyChangeListener
  //-------------------------------------------//

  //Remove a property change listener from the
  // list.
  public synchronized void
                 removePropertyChangeListener(
                   PropertyChangeListener lstnr){
    helper.removePropertyChangeListener(lstnr);
  }//end removePropertyChangeListener()
  //-------------------------------------------//

  //The following method is used to notify
  // listener objects of changes in the
  // properties.  The incoming parameters are the
  // name of the property that has changed and
  // the old value of the property.  This method
  // uses the event-firing capability of an
  // object of the PropertyChangeSupport class.
  protected void notifyPropertyChange(
                          String changedProperty,
                          Object oldValue){
    if(changedProperty.equals("theColor"))
      //Change was in theColor property
      helper.firePropertyChange(changedProperty,
                                 oldValue,color);
    else//Change was in the theDate property
      helper.firePropertyChange(changedProperty,
                                  oldValue,date);
  }//end notifyPropertyChange()

}//end class Inew2338_152Bean.java

import java.beans.*;
import java.awt.*;
import java.util.*;

class Inew2338_152
               implements PropertyChangeListener{
  String objID;

  public static void main(String[] args){
    new Inew2338_152();
  }//end main
  //-------------------------------------------//

  public void propertyChange(
                          PropertyChangeEvent e){
    System.out.println(e.getPropertyName());
    System.out.println(e.getOldValue());
    System.out.println(e.getNewValue());
  }//end propertyChange
  //-------------------------------------------//

  public Inew2338_152(){
    Inew2338_152Bean bean =
                          new Inew2338_152Bean();
    bean.addPropertyChangeListener(this);
    bean.setTheColor(Color.BLUE);
    bean.setTheColor(Color.GREEN);
    bean.setTheColor(Color.GREEN);
    try{
      Thread.currentThread().sleep(1500);
    }catch(Exception e){
      e.printStackTrace();
    }//end catch
    bean.setTheDate(new Date());
  }//end constructor

}//end class Inew2338_152

theColor
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=0,g=0,b=255]
theColor
java.awt.Color[r=0,g=0,b=255]
java.awt.Color[r=0,g=255,b=0]
theDate
Fri Oct 15 16:02:54 CDT 2004
Fri Oct 15 16:02:55 CDT 2004

Answer and Explanation



Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com


Answers and Explanations


Answer 9

True.

Explanation 9

This is a straightforward illustration of the use of bound properties.  Note that the listener is notified only when the property value changes.  Thus, setting the color property to green twice in succession results in only one notification of a property change.

You can learn more about this topic in lesson 510 at http://www.dickbaldwin.com/tocadv.htm.  Another good example of the use of bound properties is contained in lesson 107 at http://www.dickbaldwin.com/tocmed.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 9


Answer 8

True.

Explanation 8

Properties can be either simple or indexed.  A simple property has a single value.  An indexed property has multiple values, which can be accessed via an index.  This program has one simple property of type int named size and one indexed property of type int[] named indexedProp.

You can learn more about this topic in lesson 508 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 8


Answer 7

False.

Explanation 7

When the program named Inew2338_144 is used to analyze the bean class named Inew2338_148Bean,the program lists the following property names, types, and accessor methods.

Name: boolPropValue
Type: boolean
Get method: isBoolPropValue()
Set method: setBoolPropValue(boolean)
Name: color
Type: class java.awt.Color
Get method: xgetColor()
Set method: xsetColor(java.awt.Color)
Name: preferredSize
Type: class java.awt.Dimension
Get method: getPreferredSize()
Set method: null

Note in particular the names of the accessor methods for the property named color.

This program uses the class named Inew2338_148BeanBeanInfo to explicitly specify the names of the property accessor methods for all three properties.

The specified names of the accessor methods for the boolPropValue and preferredSize properties match the design patterns for property accessor method names.  However, the specified names for the accessor methods for the color property do not match the design patterns for property accessor method names.

You can learn more about the explicit specification of properties, events, and methods for a bean in lesson 766 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 7


Answer 6

False.

Explanation 6

When the program named Inew2338_146 is used to analyze the bean class named Inew2338_142Bean, the program lists the following exposed methods:

action
add
addActionListener
addComponentListener
addFocusListener
addHierarchyBoundsListener
addHierarchyListener
addInputMethodListener
addKeyListener
addMouseListener
addMouseMotionListener
addMouseWheelListener
addNotify
addPropertyChangeListener
addPropertyChangeListener
applyColorProperty
applyComponentOrientation
areFocusTraversalKeysSet
bounds
checkImage
checkImage
contains
contains
createBufferStrategy
createBufferStrategy
createImage
createImage
createVolatileImage
createVolatileImage
deliverEvent
disable
dispatchEvent
doLayout
enable
enable
enableInputMethods
equals
getAccessibleContext
getAlignmentX
getAlignmentY
getBackground
getBounds
getBounds
getBufferStrategy
getClass
getColor
getColorModel
getComponentAt
getComponentAt
getComponentListeners
getComponentOrientation
getCursor
getDropTarget
getFocusCycleRootAncestor
getFocusListeners
getFocusTraversalKeys
getFocusTraversalKeysEnabled
getFont
getFontMetrics
getForeground
getGraphics
getGraphicsConfiguration
getHeight
getHierarchyBoundsListeners
getHierarchyListeners
getIgnoreRepaint
getInputContext
getInputMethodListeners
getInputMethodRequests
getKeyListeners
getListeners
getLocale
getLocation
getLocation
getLocationOnScreen
getMaximumSize
getMinimumSize
getMouseListeners
getMouseMotionListeners
getMouseWheelListeners
getName
getParent
getPeer
getPreferredSize
getPropertyChangeListeners
getPropertyChangeListeners
getSize
getSize
getToolkit
getTreeLock
getWidth
getX
getY
gotFocus
handleEvent
hasFocus
hashCode
hide
imageUpdate
inside
invalidate
isBackgroundSet
isBoolPropValue
isCursorSet
isDisplayable
isDoubleBuffered
isEnabled
isFocusCycleRoot
isFocusOwner
isFocusTraversable
isFocusable
isFontSet
isForegroundSet
isLightweight
isOpaque
isShowing
isValid
isVisible
keyDown
keyUp
layout
list
list
list
list
list
locate
location
lostFocus
makeBlue
makeRed
minimumSize
mouseDown
mouseDrag
mouseEnter
mouseExit
mouseMove
mouseUp
move
nextFocus
notify
notifyAll
paint
paintAll
postEvent
preferredSize
prepareImage
prepareImage
print
printAll
remove
removeActionListener
removeComponentListener
removeFocusListener
removeHierarchyBoundsListener
removeHierarchyListener
removeInputMethodListener
removeKeyListener
removeMouseListener
removeMouseMotionListener
removeMouseWheelListener
removeNotify
removePropertyChangeListener
removePropertyChangeListener
repaint
repaint
repaint
repaint
requestFocus
requestFocusInWindow
reshape
resize
resize
setBackground
setBoolPropValue
setBounds
setBounds
setColor
setComponentOrientation
setCursor
setDropTarget
setEnabled
setFocusTraversalKeys
setFocusTraversalKeysEnabled
setFocusable
setFont
setForeground
setIgnoreRepaint
setLocale
setLocation
setLocation
setName
setSize
setSize
setVisible
show
show
size
toString
transferFocus
transferFocusBackward
transferFocusUpCycle
update
validate
wait
wait
wait

The large number of exposed methods in the list results from the fact that the program named Inew2338_146 uses a version of the overloaded getBeanInfo method that returns a BeanInfo object containing information about the bean class and all of its superclasses up to and including the class named Object.

You can learn more about this topic in lessons 500 through 512 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 6


Answer 5

False.

Explanation 5

When the program named Inew2338_144 is used to analyze the bean class named Inew2338_142Bean,the program lists the following property names, types, and accessor methods.

Name: boolPropValue
 Type:       boolean
 Get method: isBoolPropValue()
 Set method: setBoolPropValue(boolean)
Name: color
 Type:       class java.awt.Color
 Get method: getColor()
 Set method: setColor(java.awt.Color)
Name: preferredSize
 Type:       class java.awt.Dimension
 Get method: getPreferredSize()
 Set method: null

Note the Get method for the property named boolPropValue.  For all property types other than boolean properties, the design pattern name for the accessor method on the Get side begins with the word get (as in getColor shown above).  However, for the special case of a boolean property, the name of the accessor method on the Get side is also allowed, but not required to begin with the word is (as in isBoolPropValue).

You can learn more about this topic in lessons 500 through 512 and lesson 764 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 5


Answer 4

True.

Explanation 4

The bean class named Inew2338_142Bean defines accessor methods that meet the JavaBeans design patterns for the following properties:

You can learn more about JavaBeans design patterns in lessons 500 through 512 and lesson 766 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 4


Answer 3

True.

Explanation 3

The purpose of the program named Inew2338_144 is to use the static getBeanInfo method of the Introspector class to encapsulate information about a bean class in an object of type BeanInfo.

Once the information about the bean is encapsulated in the BeanInfo object, a variety of different methods are used to extract specific types of information about the bean from the BeanInfo object.

If the name of a bean class is not provided as a command-line parameter, the program attempts to find and analyze a bean class named JunkBean.class. 

The output is stored in a file named junk.txt.

As described earlier, the bean class named Inew2338_140Bean is a very simple bean class that barely meets the minimum requirements for a bean.  It doesn't define any properties, events, or exposed methods.  Therefore, no properties, events, or methods are reported for the bean class named Inew2338_140Bean by the program named Inew2338_144.  Thus, the output text produced by the program is as shown.

You can learn more about this topic in lessons 506 and 1060 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 3


 

Answer 2

False.

Explanation 2

While the GUI output shown is correct, the output in the command-line screen is not correct.  The correct output in the command-line screen is as shown below:

java.awt.Color[r=0,g=255,b=0]
addActionListener not fully implemented
removeActionListener not fully implemented
false

Although the color of the square is blue, the value of the color property shown in the first line of text in the above box was green when that line of text was printed. 

In fact, if you go back after clicking all the buttons as described and click the button labeled Get color property again, you will see that the value of the color property still matches the first line in the above box.  Invoking the methods that make the physical color of the square red and blue does not change the value of the color property.

The class named Inew2338_142Bean produces a skeleton bean that exhibits many of the required interface characteristics of a real bean.

Information about the interface to the bean can be provided either by adherence to design patterns, or by publishing that information in an object of a class that implements the BeanInfo interface. The Inew2338_142Bean class relies on design patterns.

When dealing with beans, we are usually interested in the properties, events, and exposed methods of the bean.  This bean has three properties with the following names:

The bean has, (or claims to have), the ability to multicast action events (although the code required to multicast those events is incomplete).

The bean exposes the following methods:

All of the methods, including those shown in black, satisfy the design requirements for exposed methods.

The methods shown in blue satisfy the design pattern requirements for event multicasting.

The methods shown in red satisfy the design pattern requirements for property setter and/or getter methods.

The purpose of the Inew2338_142 class is to test the bean named Inew2338_142Bean in a JFrame.  A Inew2338_142Bean object is placed in the frame along with nine buttons.  The visual manifestation of the bean is a colored square.

One pair of buttons exercises the "get" and "set" color properties of the bean.

Another button applies the value of the color property to the background color of the bean.

Another pair of buttons invokes the makeRed and makeBlue methods of the bean.

Another pair of buttons invokes the addActionListener and removeActionListener methods of the bean.

Another pair of buttons exercises the "set" and "is" boolean properties of the bean.

Information returned from the bean, is displayed on the standard output device.

You can learn more about JavaBeans components in lessons 500 through 512 at http://www.dickbaldwin.com/tocadv.htm.  You can learn more about JavaBeans properties in lesson 2100 at the same URL.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 2


Answer 1

True.

Explanation 1

It is my understanding that there are only two requirements for a class to be a legitimate JavaBeans component, (and I'm not even certain about the second requirement):

The class named Inew2338_140Bean satisfies both of these requirements, making it a legitimate JavaBeans component.

This class goes beyond the minimum requirement for a bean.  For example, a bean is not required to extend any particular class.  While visible beans must be a subclass of java.awt.Component so that they can be added to visual containers, this is not a requirement for invisible beans.  Since this is not a visible bean, it was not necessary for the class to extend Component.

It is also not necessary for a bean to exhibit any specific behavior, so a bean class can be entirely empty.  (An empty class would satisfy the requirement for a noarg constructor, because an empty class would have a default noarg constructor.)

You can learn more about this topic in lessons 500 through 512  at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 1


Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-