Developing a Simple Bean
This section presents an example that shows how to develop a simple, Bean and connect it to other components via the BDK. Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that is filled, with a color. A color is chosen’ at random when the Bean begins execution. A public method can be invoked to change it. Each time the mouse is clicked on the Bean, another random color is thosen. There is one boolean read/write property that determines the shape. The BDK is used to layout an application with one instance of the Colors Bean and
one instance of the Our Button Bean. The button is labeled “Change.” Each ‘time it is pressed, the ‘color changes. how this application appears.
Create a’New Bean
Here are .the steps thatt you must follow to create a new Bean:
1. Create a directory for the new Bean.
2. Create the Java source file(s).
3. Compile the source file(s).
4; Create a manifest file.
5. Generate a JAR file.
6. Start the BDK.
The following sections discus each of these steps in detail.
Create a Directory f~r he New Bean
You need to make a directory for the Bean. To follow along with this example, create
c:\bdk\demo\sunw\demo\colors. Then change to that directory. Create the Source -File for the New Bean The source code for the Colors component is shown in the following listing. It is located in the file Colors.java. ‘
The import statement at the beginning of the file places it in the package named sunw.demo.colors. Recall from Chapter 9 that the directory hierarchy corresponds to the package hierarchy. Therefore, this file must be located in a subdirectory named sunw\demo\colors relative to the CLASSPATH environment variable: The color of the component is determined by the private Color variable color, and its shape is determined by the private boolean variable rectangular. The constructor d~ines an anonymous inner Class that extends MouseAdapter and overrides its mnusef’ressedf ) method. Thechanget ) method is invoked in response to. ,mouse presses. The component is initialized to a rectangular shape of 200 by 100 pixels. The change( ) method is invoked to select a random color and repaint the component. The getRectangular( ) and setRectangular( ) methods provide access to the one property of this Bean. The changet ) method calls randomColor( ) to choose a color and then calls repaint( ) to make the change visible. Notice that the paint( ) method uses the rectangular and color variables to determine how to present theBean.