JavaBeans program development from getting started

xiaoxiao2021-03-06  42

JavaBeans properties

JavaBeans's properties and properties referred to in the general Java program, or the properties of objects in all object-oriented programming languages ​​are a concept, and the specific embodiment in the program is the variables in the class. In JavaBeans design, subdivision is divided into four categories according to different properties: Simple, INDEX, Bound and constrained properties.

SIMPLE property

A simple attribute represents a variable accompanying a pair of GET / SET methods (C language or functionality called "method" in the Java program). Attribute name and the GET / SET method name associated with this property. For example: If there is a setx and getx method, you have a property named "X". If there is a method name ISX, it usually fails to "X" is a Boolean property (ie the value of X is True or false). For example, in this program:

Public class alden1 extends canvas {

String ourstring = "hello"; // Attribute name is ourstring, type is a string

Public aldenn1 () {// Alden1 () is the constructor of Alden1,

The meaning of constructor in C

SetBackground;

SetForeground (color.blue);

}

/ * "SET" attribute * /

Public void setstring (String newstring) {

ourstring = newstring;

}

/ * "get" attribute * /

Public string getString () {

Return ourstring;

}

}

2. INDEXED attribute

A indexed property represents an array value. Use the SET / GET method corresponding to this property to get the value in the array. This property can also set or achieve the value of the entire array. example:

Public class Alden2 Extends Canvas {

int [] dataset = {1, 2, 3, 4, 5, 6}; // DataSet is an indexed property

Public Alden2 () {

SetBackground;

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;

}

/ * Acquire the entire array value * /

Public int [] getDataSet () {

Return DataSet;

}

/ * Acquired the specified element value in the array * /

Public int getDataSet (int x) {

Return DataSet [x];

}

}

3. Bound attribute

A bound property is to refer to the value of the value of the property changes. When each attribute value changes, this property is ignited to a PropertyChange event (in the Java program, the event is also an object). The attribute name, the original value of the attribute, and the new value of the attribute change are encapsulated. This event is to other Beans, as for the beans that receive events should be defined by themselves. When the pushbutton's Background property is bind with the Dialog's Background property, if the PushButton's Background property changes, the Dialog's Background property also changes. example:

Public class aldenn3 extends canvas {string ourstring = "hello";

// ourstring is a bound property

Private PropertyChangeSupport changes = new propertychangesupport (this);

/ ** Note: Java is a pure-oriented language.

If you want to use some method, you must indicate which object to use,

The operation of the ignition event is performed in the program below.

The method used in this operation is in the PropertyChangeSupport class.

So the above declared and instantified a Changes object.

In the following, you will use the Changes's FirePropertyChange method to ignit the property change event. * /

Public void setstring (String newstring) {

String oldstring = ourstring;

ourstring = newstring;

/ * Orstring's attribute value has changed, so that the ignition attribute changes event * /

Changes.firepropertyChange ("oorstring", oldstring, newstring;

}

Public string getString () {

Return ourstring;

}

/ ** The following code is used for development tools.

We can't predict that Alden3 will become an application with which other Beans combinations.

Unable to predict which other components are related to this change when Alden3's opstring property changes.

Therefore, Alden3 beans should reserve some interfaces to the development tool.

Development tools use these interfaces,

Mount other JavaBeans objects with Alden3. * /

Public Void AddPropertyChangelistener (PropertyChangelisner L) {

Changes.addpropertyChangelistener (L);

}

Public Void RemovePropertyChangeListener (PropertyChangelistener L) {

Changes.removePropertyChangeListener (L);

}

Through the above code,

Development Tool Call Changes AddPropertyChangeListener Method

Register other JavaBeans into the listener queue L of the Oudstring property,

l is a vector array that stores any Java objects.

Development tools can also use Changes's RemovePropertyChangeListener method,

Log out of the specified object from the L,

The change of the OudString property of Alden3 is no longer related to this object.

Of course, when the programmer handwritten code program,

These two methods can also be called directly.

Mount other Java objects with Alden3.

4. Constrained attribute

A JavaBeans's constrained property is that when the value of this property changes, the other Java object that has been established with this property has a change attribute value. The listener of the constrained property prevents the value of this attribute value by throwing PropertyveToException. Example: The constrained attribute in the following program is pricenetics.

Public Class Jellybeans Extends Canvas {

Private PropertyChangeSupport changes = new propertychangesupport (this);

Private VetoableChangeSupport VetOS = New VetoableChangeSupport (this); / * is the same as the aforementioned CHANGES,

Method in instance VETOS, which can use the VetoableChangeSupport object,

A change in the priceINCENTS value is prevented in a particular condition. * /

......

Public void setpriceincents (int newpriceincents) throws propertyvetoException {

/ * The role of THROWS PropertyveToException is when there is

Other Java objects veto the change of PriceINCENTS,

To throw an exception. * /

/ * Prevent the original attribute value * /

INT OLDPRICEINCENTS = OURPRICEINCENTS;

/ ** ignition attribute change veto * /

Vetos.firevetoableChange ("PriceINCents", New Integer (OldpriceInCents),

New Integer (NewPriceInCents));

/ ** If there is any other object to veto the change of PriceINCENTS,

The procedure throws an exception, no longer continues to perform the following two statements,

The method ends. If there is no other object to veto the change of PriceINCENTS,

The OurPriceInCents gives our new value in the code below.

And ignite attribute change event * /

Ourpriceincents = newpriceincents;

Changes.firePropertyChange ("PriceinCents",

New Integer (OldpriceInCents),

New Integer (NewPriceInCents));

}

/ ** is the same as the aforementioned CHANGES,

Also reserved the interface for the PriceInCents property,

Make other objects can be registered into the PriceINCents vetoing the listener queue,

Or use the object from it to

Public Void AddvetoableChangeListener (VetoableChangeListener L)

{vetos.addvetoableChangeListener (L);

}

Public Void RemoveveToableChangeListener (VetoableChangelistener L) {

Vetos.removeveToableChangeListener (L);

}

......

}

As can be seen from the above example, a constrained property has two listeners: attribute change listeners and monsoots that have changed attributes. The listener of the veto attribute changes to the corresponding control statement in its object code, and when the monitoring of the constrained property is changed, it is determined whether to veto this property value should be rejected in the control statement.

In summary, whether a beans's constrained property value may change depending on other Beans or whether the Java object allows such changes. The allowable condition is defined by other Beans or Java objects in their own class.

JavaBeans event

Event processing is one of the cores of the JavaBeans architecture. Through the event handling mechanism, some components can be made as an event source, and an event that can be described in the environment or other component can be issued. Thus, different components can be combined in the construction tool, and the components communicate between the components, constitute an application. Conceptually, an event is a transmission mechanism that changes between "source objects" and "listener objects". There are many different purposes, such as mouse events, window boundaries, etc., and keyboard events, etc., for example, in Windows systems. In Java and JavaBeans, it is defined a general, expandable event mechanism that provides a public framework for the definition and expansion of the model and the definition of the model, and is suitable for extensive applications.

There is a high integration with Java language and the environment.

The event can be described to capture and ignition.

Other constructors can take some techniques to directly control events during design, as well as between event sources and event listeners.

The event mechanism itself does not rely on complex development tools. Special, it should also:

An event that can be found in the specified object class can be found.

It can be found that the specified object class can observe (listening) the event.

Provide a regular registration mechanism that allows the relationship between the dynamic manipulation of the event source and event listener.

No need other virtual machines and languages ​​can be implemented.

Efficient event delivery between event sources and listeners.

A neutral mapping of the JavaBeans event model and the associated other component architecture event model can be completed.

The main components of the JavaBeans event model are: Events pass from the event source to the listener are passed by the Java method call to the target listener object. A clear Java method is defined accordingly for each of the clear events. These methods are centralized in the event listener (EventListener interface, this interface should inherit Java.util.EventListener. A class that implements some or all of the methods in an event listener interface is an event listener. With the occurrence of the event, the corresponding state is usually packaged in the event status object, which must inherit from Java.util.EventObject. Event status objects are transmitted to the listener method that should respond to the event as a single ginseng. The identity of the event source that issues a certain particular event is that the design format of the specified design is the registration method for event listeners and accepts references to the specified event listener interface instance. Sometimes, event listeners cannot directly implement event listener interface, or other additionalctions, it is necessary to insert an instance of an event adapter class between a source and other one or more listeners to establish them. Contact.

Event status object (Event State Object)

Status information related to the event is generally packaged in an event status object, which is a subclass of java.util.EventObject. According to the design habits, the names of this event status object class should be ended at Event. E.g:

Public class mousemovededexampleEvent extends java.util.eventObject

{protected int x, y;

/ * Create a mouse mobile event MousemoveDexampleEvent * /

MouseMoveDexampleEvent (java.awt.component source, point location) {

Super (Source);

x = location.x;

y = location.y;

}

/ * Get mouse position * /

Public Point getLocation () {

Return New Point (x, y);

}

Event listener interface (EventListener Interface) and event listener

Since the Java event model is based on method calls, a way to define and organize event handling methods. In JavaBeans, event handling methods are defined in the EventListener interface of the Java.util.EventListener class, and the naming of the EventListener interface is ended at the end of the Listener interface. Any class If you want to manipulate the method defined in the EventListener interface, you must perform this interface. This class is the event monitors. For example: / * Define a mouse mobile event object * /

Public class mousemovedexampleEvent

Extends java.util.eventObject {

/ / In this class, the state information related to the mouse movement event is included.

...

}

/ * Define the listener interface of the mouse mobile event * /

Interface MousemoveDexampleListener

Extends java.util.eventlistener {

/ * The method should support the mouse mobile event listener in this interface * /

Void MouseMoved (MousemoveDexampleEvent MME);

}

Only the method name is defined in the interface.

The parameters and return value types of the method.

Such as: the mousemoved method in the above interface

The specific implementation is defined in the following ArbitraryObject class.

Class ArbitraryObject Implements MousemovedexampleListener {

Public void mousemoved (MousemoveDexampleEvent MME)

{...}

}

ArbitraryObject is the listener of the MousemoveDexampleEvent event.

Registration and logout of event listeners

For various possible event listeners, the event streams between the source and event monitors are established in the appropriate event source, and the event source must provide registration and logout for event listeners. This use process has been seen in the previous Bound property introduction, in actual, event listener's registration and logout to use standard design format:

Public void add ( listener);

Public Void Remove ( listener);

E.g:

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 listener = new vector (); // Defines an array of storage event listeners

/ *

Public Synchronized Void AddModelchangedListener (ModelChangedListener MCL)

{Listener.AddeElement (MCL);} // Register the listener into the listeners array

Public Synchronized Void RemoveModelchangedListener (ModelchangeDlistener MCL)

{listeners.removeEleMent (MCL); // Logger listing the listener from listeners

}

/ * The front crown of the above two methods is synchronized because it is running in a multi-threaded environment.

There may be several objects at the same time to register and log out,

Use Synchronized to make sure that they are synchronized.

Developing tools or programmers use these two ways to establish event streams between source and listeners * /

protected void notifymodelchanged () {

/ ** Event source uses this method to notify the listener's modelchanged event * /

Vector L;

EventObject E = New EventObject (THIS);

/ * First, copy the listener to the L array,

Frozen the state of EventListeners to transfer events.

This way to ensure that before the event is passed to all listeners,

The corresponding method of the target listener that has received events has not taken effect. * /

Synchronized (this) {

l = (vector) listener.clone ();

}

For (int i = 0; i

/ * Introduction to the registration in the listener queue, the modelchanged event,

And transmit the event status object E as a parameter to each listener in the listener queue * /

(ModelchangeDlistener) L.Elementat (i)). ModelChanged (e);

}

}

}

In the program, the event source model class explicitly calls the modelchanged method in the interface. It is actually transmitting the event status object E as a parameter to the MODELCHANGED method in the listener class.

Adaptation class

Adaptation class is an extremely important part of the Java event model. In some applications, events are "forwarded" from the source to the transmission. For example: When an event source is issued, there are several event listener objects to receive the event, but only when the specified object reacts, an event adapter class is to be inserted between event sources and event listeners. The adapter class to specify which listeners should be responded.

The adaptation class has become an event listener. The event source actually uses the adaptation class as a listener into the listener queue, and the real event responder is not in the listener queue, the event responder should do by appropriate Classification decision. At present, most developments are generated when generating code, and event processing is made by adaptation classes.

JavaBeans User

JavaBeans developers can add a beans to the user, the property editor, and the BeansInfo interface to describe the content of Beans, Beans users can pass through these information accompanying Beans in the constructor. The appearance of the user is the appearance of beans and the action you should do. A beans don't have to have Beanscustomizer, PrperstrpertyEditor and Beansinfo, depending on the actual situation, these are optional. When some Beans is more complicated, they must provide this information, which makes Beans's users can be usernated by Wizard. Some simple beans may not have this information, then the constructor can use the self-contained perspective, see the contents of Beans, and display the information to the standard property list or event table for users to customize Beans, the first few sections The properties, methods, and event names mentioned in the mentioned Beans are named in a certain format, the main role is to make a perspective for the development tool. Of course, it is also to provide the programmer to provide convenience in handwriting, so that he can view his name and know.

User Miller Interface (Customizer Interface)

When a Beans has its own user gear, you can show your own property table within the constructor. The Java.BeanssS.customizer interface must be implemented when defining the userizer. For example, the following is a "button" Beans user-generator: Public Class OurbuttonCuStomizer

Extends Panel Implements Customizer {

...

/ * When implementing a regular properties such as OurButtonCustomizer,

Be sure to implement AddProPrChangeListener

And RemovePropertyChangelistener, this,

The constructor can add a monsoper with these functional code to attribute events. * /

...

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 the Java.beanss.PropertyEditorsupport class. The programmer of the constructor and the handwritten code does not use this class directly, but is instantiated and called this class in BeansInfo in the next section. example:

Public class moleculenameEditor Extends java.beans.propertyeditorsupport {

PUBLIC STRING [] gettags () {

String resule [] = {

"Hyaluronicacid", "Benzene", "BuckmisterFullerine",

"cyclohexane", "ethane", "water"};

Return resule;

}

In the above example, the property editor is created for the Tags property. Inside the construction tool, the properties of the MoleculeName can be selected from the drop-down table should be "Hyaluronicaid" or "Water".

Beansinfo interface

Each Beans class may also have a related BeansInfo class, which describes the appearance of this Beans in the construction tool. Properties, methods, events, display in BeansInfo, show their names, providing simple help notes. E.g:

Public class moleculebeansinfo extends simplebeansinfo {

Public propertyDescriptor [] getPropertyDescriptors () {

Try {

PropertyDescriptor PD = New PropertyDescriptor ("MoleculeName", Molecule.class;

/ * Take the MoleculeNameEditor class in the previous section through the PD, get the MoleculeName property * /

Pd.SetPropertyEditorClass (MoleculeNameEditor.class);

PropertyDescriptor result [] = {pd}; return results

} catch (exception ex) {

System.err.Println ("MoleculeBeansInfo: Unexpected Exeption: EX);

Return NULL;

}

}

}

JavaBeans persistent

When a JavaBeans is userned within the construction tool, all the status of its state should be saved, and the next time the LOAD is in the construction tool or during operation, it should be the last modification. information. In order to do this, save the information of certain fields of Beans, to define beans to implement the java.io.Serializable interface. E.g:

Public Class Button

Implements java.io.serializable {

}

The information of the fields in the beans that realize the serialization interface will be automatically saved. If you don't want to save some fields, you can crown in these fields with Transient or Static keywords, Transient and Static variables are not saved. Typically, all of the publication of a beans should be saved, or the internal state can also be selected. Beans Developers When you modify your software, you can add a field, remove references to other classes, change the private / protected / public status of a field, which does not affect the storage structure relationship of the class. However, when a field is removed from the class, change a variable in the location of the class system, change a field to transient / static, or it is transient / static, which is now changed to other features, will cause storage relationships. The change.

JavaBeans's storage format

After the Javabeans component is designed, it is generally stored in ZIP format files named JAR, contains information related to Javabeans in JAR, and specifies which classes of the Manifest file are JavaBeans. Taking JAR file stored JAR files to transmit the number of data, it is greatly reduced by data transmission, and bundles some resources required for JavaBeans runtime. This chapter mainly discusses some internal characteristics of JavaBeans and their conventional design methods, reference The JavaBeans Specification 1.0A version. As the world's large ISV is more and more support for JavaBeans, the specification is still evolving in some details, but the basic framework will not change.

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

New Post(0)