Advertisements
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. Note that the Serializable interface does not have any methods. 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.