Properties of JavaBeans
The attribute of JavaBeans is a concept in the attribute of a general Java program, or the attribute of an object in all object-oriented programming languages, which is embodied in a program as a variable in a class. In JavaBeans design, according to the different functions of the attributes are subdivided into four categories: simple, Index, bound and constrained properties.
1. Simple properties
A simple property represents a variable that accompanies a pair of get/set methods (the C language procedure or function is called a "method" in a Java program). The property name corresponds to the Get/set method name associated with the property. For example, if there is a setx and getx method, it implies a property named "X". If there is a method named ISX, it usually implies that "X" is a Boolean property (that is, the value of x is True or false). For example, in the following program:
public class Alden1 extends Canvas {
String ourstring= "Hello"; Property name is Ourstring, type is string
The public alden1 () {//alden1 () is the Alden1 constructor.
Same as the meaning of constructors in C + +
SetBackground (color.red);
Setforeground (Color.Blue);
}
/* "Set" Property * *
public void SetString (String newstring) {
ourstring=newstring;
}
/* "Get" Property * *
Public String getString () {
return ourstring;
}
}
2. Indexed properties
A indexed property represents an array value. Use the Set/get method that corresponds to this property to get the numeric value in the array. The property can also set or get the value of the entire array at one time. Cases:
public class Alden2 extends Canvas {
Int[] dataset={1,2,3,4,5,6}; A dataset is a indexed property
Public Alden2 () {
SetBackground (color.red);
Setforeground (Color.Blue);
}
/* Set the entire array * *
public void Setdataset (int[] x) {
Dataset=x;
}
/* Set a single element value in the array/*
public void Setdataset (int index, int x) {
Dataset[index]=x;
}
/* Get the entire array value * *
Public int[] GetDataSet () {
return dataSet;
}
/* Gets the specified element value in the array * *
public int GetDataSet (int x) {
return dataset[x];
}
}
3. Bound properties
A bound property refers to the notification of other objects when the value of that property is changed. Each time the property value changes, this property fires a PropertyChange event (in Java program, an event is also an object). The event encapsulates the property name, the original value of the property, and the new value after the property has changed. This event is passed on to other beans, as to what the beans of the event should do by its own definition. When the background attribute of pushbutton is bind to the background attribute of dialog, the Pushbutton property of background also changes when dialog property of background is changed. Cases:
public class Alden3 extends canvas{
String ourstring= "Hello";
Ourstring is a bound property
Private Propertychangesupport changes = new Propertychangesupport (this);
/** Note: Java is a pure object-oriented language,
If you want to use a method, you must indicate which object you want to use.
The operation of the ignition event in the following program,
The method used in this operation is in the Propertychangesupport class.
So it declares and instantiates a changes object,
The changes Firepropertychange method is used below to ignite the Ourstring property Change event. */
public void SetString (string newstring) {
String oldstring = ourstring;
ourstring = newstring;
/* Ourstring property value has changed, so the ignition property changes the event * *
Changes.firepropertychange ("ourstring", oldstring,newstring);
}
Public String getString () {
return ourstring;
}
/** The following code is used for development tools.
We cannot foresee what other beans combinations Alden3 will become an application,
There is no way to predict what other components are associated with this change if the Alden3 ourstring attribute changes.
So alden3 this beans to set aside some interfaces for development tools,
Development tools use these interfaces,
Hook up the other JavaBeans objects with the Alden3. */
public void Addpropertychangelistener (Propertychangelisener l) {
Changes.addpropertychangelistener (l);
}
public void Removepropertychangelistener (PropertyChangeListener l) {
Changes.removepropertychangelistener (l);
}
Through the code above, the development tool calls the changes Addpropertychangelistener method, registers the other JavaBeans in the listener queue L of the Ourstring property, and L is a vector array that stores any Java object.
The development tool can also use the changes Removepropertychangelistener method to unregister the specified object from L, so that changes to the Ourstring property of Alden3 are no longer associated with this object.
Of course, when programmers write code, they can call these two methods directly to hook up other Java objects with Alden3.
4. Constrained properties
A JavaBeans constrained property, which means that when the value of this property is to change, other Java objects that have established a connection with this property can veto the change in the value of the property. The listener for the constrained property prevents the property value from being changed by throwing a propertyvetoexception. Example: the constrained property in the following program is priceincents.
public class Jellybeans extends canvas{
Private Propertychangesupport changes=new Propertychangesupport (this);
Private Vetoablechangesupport vetos=new Vetoablechangesupport (this);
/* is the same as the aforementioned changes,
You can use the method in the instance Vetos of the Vetoablechangesupport object,
To prevent the change of priceincents values in certain conditions. */
......
public void setpriceincents (int newpriceincents) throws Propertyvetoexception {
/* The function of throws Propertyvetoexception in the method name is when there is
When other Java objects veto priceincents changes,
to throw an exception. */
/* First save the original attribute value * *
int oldpriceincents=ourpriceincents;
/** Ignition Attribute Change Veto event * *
Vetos.firevetoablechange ("Priceincents", New Integer (oldpriceincents), new Integer (newpriceincents);
/** if any other object rejects the priceincents change,
The program throws an exception and does not continue with the following two statements.
Method ends. If no other object rejects the priceincents change,
The ourpriceincents is given a new value in the following code.
and Ignition Properties Change Event * *
ourpriceincents=newpriceincents;
Changes.firepropertychange ("Priceincents", New Integer (oldpriceincents), new Integer (newpriceincents);
}
/** is the same as the aforementioned changes,
You also want to reserve an interface for the Priceincents property,
Enables other objects to be registered in the priceincents veto change listener queue,
Or unregister the object from the
public void Addvetoablechangelistener (Vetoablechangelistener l)
{
Vetos.addvetoablechangelistener (l);
}
public void Removevetoablechangelistener (Vetoablechangelistener l) {
Vetos.removevetoablechangelistener (l);
}
......
}
As you can see from the example above, there are two types of listeners for a constrained attribute: The property change listener and the listener who rejects the attribute change. The listener who rejects the attribute change has a corresponding control statement in its object code, and in the control statement it is judged whether the change in the attribute value should be rejected when the constrained attribute is heard to change.
In summary, whether a beans's constrained attribute value can be changed depends on the other beans or if the Java object allows the change. The conditions allowed are defined by other beans or Java objects in their own classes.
JavaBeans's Events
Event handling is one of the core of JavaBeans architecture. The event-handling mechanism allows some components to act as event sources, emitting events that can be received by a descriptive environment or other component. In this way, different components can be grouped together within the construction tool, and the components communicate through the passing of events to form an application. Conceptually, an event is a passing mechanism between the "source object" and the "listener object", in which a state has changed. Events can be used for many different purposes, such as mouse events that are often handled in Windows systems, window boundary changes, keyboard events, and so on. In Java and JavaBeans, you define a generic, extensible event mechanism that can:
• Provides a common framework for the definition and expansion of event types and transitive models, and is suitable for a wide range of applications.
• A high degree of integration with the Java language and environment.
• Events can be described as environmental capture and ignition.
• Enables other construction tools to take some technology to directly control the event at design time, and the connection between the event source and the event listener.
• The event mechanism itself does not depend on complex development tools. In particular, it should also:
• The ability to discover events that can be generated by specified object classes.
• The ability to discover events that the specified object class can observe (monitor).
• Provides a regular registration mechanism that allows dynamic manipulation of the relationship between event sources and event listeners.
• No other virtual machines and languages are required.
• Efficient event delivery between an event source and a listener.
• Can complete the neutral mapping of the JavaBeans event model and related other component architecture event models.
The main composition of the JavaBeans event model is that the event is passed from the event source to the listener through a Java method call to the target listener object. A clear Java method is defined accordingly for each specific occurrence of the event. These methods are centrally defined in the event Listener (EventListener) interface, which inherits Java.util.EventListener. The class that implements some or all of the methods in the event listener interface is the event listener. Along with the occurrence of events, the corresponding states are usually encapsulated in the event state object, which must inherit from the Java.util.EventObject. The event state object is passed as a single parameter to the listener method that should respond to the event. An event source that emits a particular event is identified by following the specified design format, defining the registration method for the event listener, and accepting a reference to the specified event listener interface instance. Sometimes, an event listener cannot implement the event listener interface directly, or if there are other additional actions, it is necessary to establish a connection between one source and one or more listeners by inserting an instance of the event adapter class.
Event State Object
State information related to event occurrence is generally encapsulated in an event state object, which is a subclass of Java.util.EventObject. By design practice, the name of this event state object class should end with an event. For example:
public class Mousemovedexampleevent extends Java.util.EventObject
{
protected int x, y;
/* Create a mouse movement event mousemovedexampleevent * *
Mousemovedexampleevent (java.awt.Component source, point location) {
Super (source);
x = location.x;
y = location.y;
}
/* Get mouse position * *
Public Point getLocation () {
Return to New Point (x, y);
}
}
Event Listener Interface (EventListener Interface) and Event Monitor listener
Because the Java event model is based on method calls, a way to define and organize event manipulation methods is required. In JavaBeans, the event manipulation method is defined in the EventListener interface that inherits the Java.util.EventListener class, and as a rule, the EventListener interface is named to end with listener. Any class that wants to manipulate the methods defined in the EventListener interface must do so in the way that the interface is implemented. This class is also the event listener. For example:
/* First defines a mouse movement event object.
public class Mousemovedexampleevent
Extends Java.util.EventObject {
Contains status information related to mouse movement events in this class
...
}
/* The Listener interface that defines the mouse movement event * *
Interface Mousemovedexamplelistener
Extends Java.util.EventListener {
/* Defines the method that the mouse mobile event listener should support in this interface * *
void mousemoved (mousemovedexampleevent Mme);
}
Only the method name, the parameter of the method, and the return value type are defined in the interface. For example, the concrete implementation of the Mousemoved method in the above interface is defined in the Arbitraryobject class below.
Class Arbitraryobject implements Mousemovedexamplelistener {
public void mousemoved (mousemovedexampleevent Mme)
{ ... }
}
Arbitraryobject is the listener of the Mousemovedexampleevent event.
Registration and cancellation of event listeners
For all possible event listeners to register themselves in the appropriate event source, establish the flow of events between source and event listeners, and the event source must provide a way for the event listener to register and unregister. This usage has been seen in the previous bound attribute introduction, in which the registration and logoff of event listeners is used in a standard design format:
public void add< listenertype> (< listenertype> listener);
public void remove< listenertype> (< listenertype> listener);
For example:
First, an event listener interface is defined:
public interface
Modelchangedlistener extends Java.util.EventListener {
void modelchanged (EventObject e);
}
then define the event source class:
Public abstract class Model {
Private vector listeners = new vector (); Defines an array that stores event listeners
/* The < listenertype> in the above design format is the modelchangedlistener*/below
Public synchronized void Addmodelchangedlistener (Modelchangedlistener MCL)
{listeners.addelement (MCL);} Register the Listener in the listeners array
Public synchronized void Removemodelchangedlistener (Modelchangedlistener MCL)
{listeners.removeelement (MCL);//write off the listener from the listeners
}
/* Above two methods are preceded by synchronized,
is because when running in a multithreaded environment,
You may have several objects that you want to register and unregister at the same time.
Use synchronized to ensure synchronization between them.
Development tools or programmers use these two methods to create an event flow between source and listener.
protected void notifymodelchanged () {
/** Event Source Using this method notifies the listener that a modelchanged event has occurred.
Vector l;
EventObject e = new EventObject (this);
/* First to copy the listener to the L array,
Freezes the state of the eventlisteners to pass events.
So to ensure that the event is passed to all Tong ?
The corresponding method for the target listener who has received the event is not valid. */
Synchronized (this) {
L = (Vector) listeners.clone ();
}
for (int i = 0; i < l.size (); i++) {
/* Notifies each listener registered in the listener queue, in turn, that a modelchanged event has occurred.
The event Status Object E is passed as a parameter to each listener in the listener queue.
((Modelchangedlistener) L.elementat (i)). Modelchanged (e);
}
}
}
In the program visible event source model class explicitly calls the Modelchanged method in the interface, in fact, the event state object E As a parameter, passed to the Listener class Modelchanged method.
Fit Class
The adapter class is an extremely important part of the Java event model. In some applications, the transfer of events from source to listener is "forwarded" through the adapter class. For example, when an event source issues an event, and a few event listener objects can receive the event, but only when the specified object responds, an event adapter class is inserted between the event source and the event listener, and the adapter class specifies which listeners should respond to the event.
The adaptation class becomes the event listener, and the event source actually registers the adapter class as the listener in the listener queue, while the real event responder is not in the listener queue, and the action of the event responder is determined by the adaptation class. At present, most of the development tools in the generation of code, event processing is done through the adaptation class.
JavaBeans of users
JavaBeans developers can give a beans add user (Customizer), property Editor (PropertyEditor) and Beansinfo interface to describe a beans content. Beans users can use this information that comes with beans in a construction environment to beans the look and actions that should be done. A beans does not have to have Beanscustomizer, Prpertyeditor, and Beansinfo, which, according to the actual situation, are optional, and when some beans are more complex, this information should be provided, Enables Beans users to wizard a beans in a way that allows them to be used. Some simple beans may not have this information, the constructor can use its own perspective device to perspective the contents of the beans and display the information in a standard property sheet or event table for the user to beans, and the beans properties, methods, and event names mentioned in the previous sections are named in a certain format. The main role is for the development tool to beans perspective. Of course, it is also convenient for programmers to use beans in handwritten programs, so that he can see his name and know his meaning.
user Interface (Customizer Interface)
When a beans has its own user, it can display its own property sheet within the construction tool. Java must be implemented when defining a user. Beanss.customizer interface. For example, the following is a user-beans of a "button":
public class Ourbuttoncustomizer
Extends Panel implements Customizer {
... ...
/* When the real phenomenon ourbuttoncustomizer such a general property sheet,
Be sure to implement Addproperchangelistener in them
And Removepropertychangelistener, so that
The constructor tool can use these feature codes to add listeners to a property event. */
... ...
Private Propertychangesupport changes=new Propertychangesupport (this);
public void Addpropertychangelistener (PropertyChangeListener l) {
Changes.addpropertychangelistener (l);
public void Removepropertychangelistener (PropertyChangeListener l) {
Changes.removepropertychangelistener (l);
}
... ...
Property Editor Interface (PropertyEditor Interface)
A JavaBeans can provide a propertyeditor class that creates an editor for the specified property. This class must inherit from Java. Beanss.propertyeditorsupport class. Programmers who construct tools and handwriting code do not use this class directly, but rather instantiate and invoke this class in the Beansinfo in the next section. Cases:
public class Moleculenameeditor extends Java. Beanss.propertyeditorsupport {
Public string[] GetTags () {
String resule[]={
"Hyaluronicacid", "benzene", "buckmisterfullerine", "cyclohexane", "ethane", "Water"};
return resule;}
}
In the example above, a property editor is created for the Tags property, and in the constructor tool, you can select from the Drop-down table that the Moleculename attribute should be "hyaluronicaid" or "water".
Beansinfo Interface
Each beans class may also have a beansinfo class associated with it, which describes the appearance of the beans when it appears inside the constructor tool. In Beansinfo, you can define properties, methods, events, display their names, and provide a simple help note. For example:
public class Moleculebeansinfo extends Simplebeansinfo {
Public propertydescriptor[] Getpropertydescriptors () {
try {
PropertyDescriptor pd=new PropertyDescriptor ("Moleculename", Molecule.class);
/* The Moleculenameeditor class in the previous section is referenced through PD, and the Moleculename property is obtained and returned.
Pd.setpropertyeditorclass (Moleculenameeditor.class);
PropertyDescriptor RESULT[]={PD};
return result;
catch (Exception ex) {
System.err.println ("moleculebeansinfo:unexpected exeption:" +ex);
return null;
}
}
}
JavaBeans Persistence
When a JavaBeans is instantiated within a construction tool and connected to other beans, all its states should be saved, the next time it is load into the constructor tool, or at run time, it should be the last modified information. In order to do this, the information of some fields of beans should be saved, and the beans should be implemented java.io.Serializable interface when defining. For example:
public class Button
Implements Java.io.Serializable {}
The information for the fields in the beans that implements the serialization interface is automatically saved. If you do not want to save information for some fields, you can prefix these fields with transient or static keywords, and the information for transient and static variables cannot be saved. In general, all publicly available attributes of a beans should be saved, and the internal state can optionally be saved. Beans developers to modify the software, you can add fields, remove references to other classes, change the private/protected/public state of a field, which does not affect the class's storage structure relationship. However, when you remove a field from a class, change the position of a variable in the class system, change a field to transient/static, or transient/static, and change to a different feature, the storage relationship changes.
storage format for JavaBeans
When the JavaBeans component is designed, it is typically stored in a zip-format file with an extension jar, contains information about JavaBeans in the jar, and specifies which of these classes are JavaBeans in the manifest file. The JavaBeans of jar file storage greatly reduces the number of data transmitted in the network, and binds some resources required by JavaBeans runtime, this chapter mainly discusses some internal characteristics of JavaBeans and its conventional design methods, Reference is the JavaBeans specification 1.0A version. As the world's major ISVs support JavaBeans more and more, the specification is evolving in some detail, but the basic framework will not change much.