Use of JavaBean
Redistribution or reuse of code and code compartmentalization are the two basic reasons why the java beans technology came into existence. With the help of the java beans technology, a person can create an entire application by simply using a graphical tool to connect some bean components together.
Bean Development Kit
The Java Bean Development Kit (BDK), according to Sun Microsystems, is intended to support the development of JavaBeans components and to act as a standard reference base for both component developers and tool vendors. The BDK includes a BeanBox, which is the JavaBeans reference container and acts as an example of how to build your own bean container. The Beanbox however is not an application development tool. It allows you to test the functionality of your Bean components including properties and events.
BeanBox
BeanBox is a basic tool that Sun provides for testing Java Beans. To run the BeanBox, your computer needs to have access to a BDK installation. To run the BeanBox, go to the beans/beanbox subdirectory and then type run. This will bring up three windows:
-
The ToolBox window gives you a palette of sample Java Beans to choose from.
-
The BeanBox window is a container within which you can visually wire beans together.
-
The Properties window allows you to edit the properties of the currently selected Java Bean.
Creating a Java Bean
This example illustrates how to create a simple Java Bean. Java Bean classes must be made Serializable so that they support persistent storage. To make use of the default serialization capabilities in Java, the class needs to implement the Serializable interface or inherit a class that implements the Serializable interface. It just serves as a flag to say that the designer has tested the class to make sure it works with default serialization. Here is the code:
SimpleBean.java
|
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);
}
}
|
Since this class extends a GUI component, java.awt.Canvas, it will be a visible Java Bean. Java Beans may also be invisible. Now the Java Bean must be compiled and packaged into a JAR file. First run the compiler: javac SimpleBean.java Then create a manifest file manifest.tmp Name: SimpleBean.class Java-Bean: True Finally create the JAR file: jar cfmv SimpleBean.jar manifest.tmp SimpleBean.class. The JAR file can now be placed in the beans/jars so that the BeanBox will find it on startup, or it can be loaded subsequently by choosing File | LoadJar. |