JavaBeans program development from introductory to proficient tutorial refinement

Source: Internet
Author: User
Tags add format define end event listener numeric value string variable
Program | Tutorial JavaBeans Properties

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 public alden1 () {//alden1 () Is the Alden1 constructor, which is the same as the meaning of the constructor in C + + setbackground (color.red); Setforeground (Color.Blue); }/* "Set" Property */public void setstring (String newstring) {ourstring=newstring}/* "Get" property/* Public String getString () {RE Turn ourstring; } }
       
        


2, indexed property

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};//DataSet is a indexed property public Alden2 () {SetBackground (Co lor.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) {D Ataset[index]=x; /* Get the entire array value/public int[] GetDataSet () {return dataSet;}/* Get the specified element value in the array/public int getdataset (int x) {return datase T[X]; } }
       
        


3, bound property

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 Propertychangesu Pport changes = new Propertychangesupport (this); /** Note: Java is a pure object-oriented language, if you want to use a method you must indicate which object to use the method, in the following program to carry out the operation of the ignition event, the operation of the method used in the Propertychangesupport class. Therefore, a changes object is declared and instantiated, and the changes Firepropertychange method is used to ignite the Ourstring property Change event below. */public void setstring (string newstring) {string oldstring = ourstring; ourstring = newstring;/* Ourstring property values have changed, and then Ignition Property Change Event/Changes.firepropertychange ("ourstring", oldstring,newstring); The 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, and what other components are associated with this change if the ourstring attribute of Alden3 changes, so alden3 this beans to set aside some interfaces for development tools, The development tool uses these interfaces to hook up 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 Addpropertychangelistener method that the development tool calls changes

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

L is an array of vectors that can store any Java object.

Development tools can also use the changes Removepropertychangelistener method,

Unregister the specified object from L.

Changes to the Alden3 ourstring property are no longer associated with this object.

Of course, when a programmer writes a code script,

You can also call these two methods directly,

Hook up other Java objects with the Alden3.

4, constrained property

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 V Etoablechangesupport vetos=new Vetoablechangesupport (this); /* is the same as the previous changes, you can use the method in the instance Vetos of the Vetoablechangesupport object to prevent the priceincents value from changing in certain conditions. * * * ... public void setpriceincents (int newpriceincents) throws propertyvetoexception{/* method name throws The role of Propertyvetoexception is to throw exceptions when there are other Java objects that veto priceincents changes. /** Ignition Attribute Change reject Event/Vetos.firevetoablechange ("Priceincents", New Integer (oldpriceincents), new Integer (newpriceincents) ); /** If there are other objects that veto priceincents changes, the program throws an exception and no longer executes the following two statements, and the method ends. If no other object rejects the change of priceincents, the ourpriceincents is given a new value in the following code, and the ignition property changes the event/ourpriceincents=newpriceincents; Changes.firepropertychange ("Priceincents", New Integer (oldpriceincents), new Integer (newpriceincents); /** is the same as the previous changes, also to reserve an interface for the Priceincents property, so that other objects can be registered in the priceincents veto change listener queue, or log the object from 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:

The definition and expansion of event types and transitive models provides a common framework and is suitable for a wide range of applications.

Has 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 control the event directly 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:

Can discover events that can be generated by the specified object class.

Can discover events that the specified object class can observe (listen to).

Provides a general registration mechanism that allows dynamic manipulation of the relationship between event sources and event listeners.

No other virtual machines and languages are required to achieve this.

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 components of the JavaBeans event model are:

An 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 Mousemovedexampleeventextends 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 points 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 state information about the mouse movement event in this class ...    . /* * The Listener interface that defines mouse movement events/Interface Mousemovedexamplelistener extends Java.util.EventListener {/* is defined in this interface by the mouse mobile event listener The method of * * void mousemoved (mousemovedexampleevent Mme); }
       
        



Only the method name is defined in the interface.

The parameter and return value type of the method.

For example: 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 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:

       
        
The public abstract class Model {private Vector listeners = new vector ();//defines an array that stores event listeners/* The < listenertype> in the design format above Here is the following modelchangedlistener*/public synchronized void Addmodelchangedlistener (Modelchangedlistener MCL) { Listeners.addelement (MCL);} Register the Listener in the listeners array public synchronized void Removemodelchangedlistener (Modelchangedlistener MCL) {Listeners.remov Eelement (MCL); Remove the listener from the listeners}/* Above two methods are preceded by synchronized, because when running in a multithreaded environment, there may be several objects at the same time to register and logoff operations, using synchronized to ensure synchronization between them.      The development tool or programmer uses these two methods to establish the event flow between source and listener/protected void notifymodelchanged () {/** Event source notifies the listener that a modelchanged event has occurred/Vector l using this method; EventObject e = new EventObject (this); /* First copy the listener to the L array, freezing the state of the eventlisteners to pass the event. This ensures that the corresponding method for the target listener who has received the event is not valid until the event is passed to all listeners.      * * Synchronized (this) {L = (Vector) listeners.clone ();  for (int i = 0; i < l.size (); i++) {/* to sequentially notify each listener registered in the listener queue that a modelchanged event occurred and pass the event status Object e as a parameter to each listener in the listener queue. * ((Modelchangedlistener) L.elementat (i)). modelchanged (e); }     }     }
       



Visible Event source in the program the model class explicitly invokes the Modelchanged method in the interface, actually passing the event state object E as a parameter to the Modelchanged method in the Listener class. The

Fit Class

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

Adapter class becomes an event listener, and the event source actually registers the adapter class as a 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 adapter class. At present, most of the development tools in the generation of code, event processing is done through the adaptation class.

JavaBeans user

JavaBeans developers can describe a propertyeditor to a beans add a user (Customizer), a property editor (Beansinfo), and a beans interface , beans users can beans the appearance of beans and the action to be made in a structured environment by using this information that comes with the same message.

A beans does not have to have Beanscustomizer, Prpertyeditor, and Beansinfo, which, depending on the circumstances, are optional, and when some beans are more complex, this information is 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, perspective the contents of the beans, and display the information in a standard property sheet or event table for the user to beans, the beans properties mentioned in the previous sections, Methods and event names should be named in a certain format, and the main function is for the development tool to beans. 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 and removepropertychangelistener in them so that the constructor tool can add listeners to the property events. */... private propertychangesupport changes=new propertychangesupport (this); public void Addpropertychangelistener (PropertyChangeListener l) {Changes.addpropertychangelistener (L); 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 Moleculebeansinfoextends Simplebeansinfo {public propertydescriptor[]getpropertydescriptors () {try { PropertyDescriptor pd=newpropertydescriptor ("Moleculename", Molecule.class); /* The Moleculenameeditor class in the previous section is referenced through PD, and the Moleculename property/Pd.setpropertyeditorclass (Moleculenameeditor.class) is obtained and returned. 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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.