Making Beans

At the highest level, the steps for creating a Java Bean can be summed up like this:
(This is, of course, overly simplistic, but we have to start somewhere.)


The steps necessary for using a Bean at design time:


A Very Simple Bean

Here is the code for a simple bean.
import java.awt.*;
import java.io.Serializable;

public class SimpleBean extends Canvas implements Serializable {
  // Constructor sets inherited properties
  public SimpleBean() {
    setSize(60,40);
    setBackground(Color.red);
  }
}
Some things to notice about this code:


A Very Simple Bean - JAR file

After you've written and compiled the code for your Bean, the next step is to create a JAR file that can be used to distribute it. The JAR file for a Bean should contain all of its .class files, as well as any resource files such as the image file that will be its icon in a builder tool, or any other image or sound files that it uses. It should also contain the BeanInfo class, if there is one. For example, if you listed the contents of "juggler.jar", you would see the following:
META-INF/MANIFEST.MF
sunw/demo/juggler/Juggler.class 
sunw/demo/juggler/JugglerBeanInfo.class
sunw/demo/juggler/Juggler0.gif
sunw/demo/juggler/Juggler1.gif 
sunw/demo/juggler/Juggler2.gif 
sunw/demo/juggler/Juggler3.gif 
sunw/demo/juggler/Juggler4.gif
sunw/demo/juggler/JugglerIcon.gif 


For the SimpleBean we're creating, the JAR is simply:
META-INF/MANIFEST.MF
sunw/demo/juggler/SimpleBean.class 
One very important point about the JAR file for a Bean: You need to provide explicit manifest entries in order to identify any Beans in the JAR file. How?
Here is a sample makefile that could be used both to compile your Bean code and generate its JAR file.


Another Bean

This bean is not much more complicated than the previous one. But instead of merely inheriting the properties of its superclass, it has one of its own.

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

public class SimpleBean2 extends Canvas implements Serializable {

private Color color = Color.green;

  // Constructor sets inherited properties
  public SimpleBean2() {
    setSize(60,40);
    setBackground(Color.red);
  }

  public Color getColor() {
    return color;
  }

  public void setColor(Color newColor) {
    color = newColor;
    repaint();
  }

  public void paint(Graphics g) {
    g.setColor(color);
    g.fillRect(20,5,20,30);
  }
}
Some things to notice about this code:
  • It has the code to implement a property, Color.
  • It does this by providing "getter" and "setter" methods that strictly follow the design pattern for simple properties.
  • The class implements Serializable, not explicitly, but by virtue of the fact that its superclass is Canvas.