Javabean 101 10

zhaozj2021-02-11  252

Javabean 101, Part 2 (2)

Author: Beth Stearns / Liaozheng Date: March 8, 2001

Create a bean

If you want to learn to create a bean, the easiest way is to learn to create a basic bean, then add an attribute to the bean. The simplest bean must implement a java.io.serializable interface. In fact, in the default, any Java class that implements the Serializable interface is a minimum javabean. For example, a simple bean that only shows the red rectangle is extended from the AWT component java.awt.canvas. The bean itself only needs to define a constructor to set the size of the rectangle and set the background color of the matrix to red.

Create a simple bean

Let's start with a created bean, this bean defines a known size in its constructor, which is red. In the red rectangle, there is a green small rectangle. In addition to defining the constructor, the bean also includes a simple attribute called Color, which is green. Note: The Color property in this bean is illustrated as private.

BEAN includes two public (public) methods, one is used to obtain the attribute value, and the other is used to set the value value. Because the Color property is private, it cannot be accessed directly, so it can only be accessed through these Getter and Setter methods. The following is the source code of Javabean named SimpleBean:

Import java.awt. *;

Import java.io.serializable; Public Class SimpleBean Extends Canvas

IMPLEMENTS SERIALIZABE {

PRIVATE color color = color.green;

// Getter Method

Public color color getcolor () {

Return Color;

}

// setter method

Public void setcolor (color newcolor) {

Color = newcolor;

Repaint ();

} // Override Paint Method

Public void paint (graphics g) {

G.SetColor (color);

g.fillRect (20, 5, 20, 30);

} // Constructor: Sets inherited Properties

Public SimpleBean () {

Setsize (60, 40);

SetBackground;

}

}

转载请注明原文地址:https://www.9cbs.com/read-4759.html

New Post(0)