Deep understanding of JAVA event mechanism

Source: Internet
Author: User

Participants of the event mechanism in Java have three roles:

1. event object: event state object, which is used in the corresponding listener method. As a parameter, it usually exists in the method with listerner.

2. Event Source: the specific event source. For example, if you click a button, the button is the event source. To make the button respond to some events, you need to register a specific listener.

3. Event listener: Specifies the event class to be listened to. When it monitors the event object generation, it calls the corresponding method for processing.

Let's take a look at the event package provided by JDK:
Public interface eventlistener: The tag interface that must be extended for all event listener interfaces.
Public class eventobject extends object implements serializable
All event status objects are derived from the root class. All events reference the object "Source" during construction. Logically, this object is considered to be the first event-related object.

When processing events in Java2, The dispatchevent ()-postevent ()-handleevent () method is not used. The Listener class is used, and each event class has an associated listener interface. The transfer of an event from the event source to the listener is performed by calling the Java method of the target listener object.

A specific Java method is defined for the occurrence of each specific event. These methods are centrally defined in the event listener interface, which inherits java. util. eventlistener. The class that implements some or all of the methods of the event listener interface is the event listener.

With the occurrence of an event, the corresponding State is usually encapsulated in the event state object, which must inherit from java. util. EventObject. The event status object is passed as a single parameter to the listener method responding to the event. The identifier of the event source that generates a specific event is: follow the prescribed design format to define the registration method for the event listener and accept references to the instance of the specified event listener interface.

First, I would like to ask a question: Are you familiar with java. util. EventObject and java. util. EventListener classes and their existing subclasses?

If you are already familiar with the event listeners that jdk provides for us and are familiar with the events that jdk has prepared for us, such as MouseEvent, KeyEvent, and javaswevent, you must have an understanding of java's event mechanism. However, you may still feel that it is okay to use it, but the principle is still a bit confused, so let's further implement these events and listeners, that is, custom events.

In fact, custom events are very useful in java. Sometimes we want our programs to generate an event, but we don't want (or can't) to use the mouse, keyboard and other input devices, for example, if you write an application, in this program, once you receive the email, the relevant processing of the mail, for the "received mail" event, jdk is not defined. For such events and listeners of such events, we can only do it by ourselves.

Next we will start our "Innovation" process with an instance: first, the EventObject class is used as the parent class to generate our own event class, And the EventListener interface is used to implement our own listener; the rest is how to register these events and test them.

Bytes --------------------------------------------------------------------------------------------------------------------------

(1) create a DoorEvent class through the DoorEvent. java file. This class inherits EventObject.

/**
* Defines event objects and must inherit EventObject
*/
Package test;
Import java. util. eventobject;
Public class doorevent extends eventobject {
Private string doorstate = ""; // indicates the door status, which can be "on" or "Off ".

Public doorevent (Object source, string doorstate ){
Super (source );
This. doorstate = doorstate;
}

Public void setdoorstate (string doorstate ){
This. doorstate = doorstate;
}

Public String getdoorstate (){
Return this. doorstate;
}
}

Bytes ----------------------------------------------------------------------------------------------------------------------------
(2) define a new event listening interface, which inherits from EventListener. This interface contains a handler for doorEvent events:

/**
* Defines the listening interface and monitors DoorEvent events.
*/
Package test;
Import java. util. EventListener;
Public interface DoorListener extends EventListener {
Public void doorEvent (DoorEvent event );
}

Through the above interface, we define the event listening class, which specifically implements the listening and event processing functions.

/**
* This class is the implementation of the door 1 listening interface. The door opening and closing actions are performed.
*/
Package test;
Public class DoorListener1 implements DoorListener {
Public void doorEvent (DoorEvent event ){
If (event. getDoorState ()! = Null & event. getDoorState (). equals ("open "))
{
System. Out. println ("Door 1 open ");
}
Else
{
System. Out. println ("Door 1 closed ");
}
}
}

/**
* This class is the implementation of the door 2 listening interface. It is used to open, close, and turn on and turn off the light.
*/
Package test;
Public class doorlistener2 implements doorlistener {
Public void doorevent (doorevent event ){
If (event. getdoorstate ()! = NULL & event. getdoorstate (). Equals ("open "))
{
System. Out. println ("Door 2 open, while opening the corridor light ");
}
Else
{
System. Out. println ("Doors 2 off, while the corridor lights off ");
}
}
}

Bytes ---------------------------------------------------------------------------------------------------------------------------

(3) create an event source class through doormanager. java. It uses a collection listeners object to store all event listener objects. The storage method is through adddoorlistener. Policylisteners (...) is the method used to trigger an event. It is used to notify the system that an event has occurred. Call the corresponding processing function.

/** <Br/> * event source object. Here you can think of it as a remote control that controls the opening and closing of the door. <br/> * (if it is in swing, similar to a button) <br/> */<br/> package test; <br/> Import Java. util. *; <br/> public class doormanager {<br/> private collection listeners; <br/>/** <br/> * Add event <br/> * @ Param listener doorlistener <br/> */<br/> Public void adddoorlistener (doorlistener listener) {<br/> If (listeners = NULL) {<br/> listeners = new hashset (); <br/>}< br/> listeners. add (listener ); <br/>}</P> <p>/** <br/> * remove event <br/> * @ Param listener doorlistener <br/> */<br/> Public void removedoorlistener (doorlistener listener) {<br/> If (listeners = NULL) <br/> return; <br/> listeners. remove (listener ); <br/>}</P> <p>/** <br/> * trigger the door opening event <br/> */<br/> protected void fireworkspaceopened () {<br/> If (listeners = NULL) <br/> return; <br/> doorevent event = new doorevent (this, "open "); <br/> policylisteners (event ); <br/>}</P> <p>/** <br/> * trigger a close event <br/> */<br/> protected void fireworkspaceclosed () {<br/> If (listeners = NULL) <br/> return; <br/> doorevent event = new doorevent (this, "close "); <br/> policylisteners (event ); <br/>}</P> <p>/** <br/> * notify all doorlistener <br/> */<br/> private void policylisteners (doorevent event) {<br/> iterator iter = listeners. iterator (); <br/> while (ITER. hasnext () {<br/> doorlistener listener = (doorlistener) ITER. next (); <br/> listener. doorevent (event); <br/>}</P> <p>

Bytes --------------------------------------------------------------------------------------------------------------------------

(4) Okay. Finally, write a test program to test our custom events. This program should be easy to understand :)

/**
* The main program is like the person who wants to open the door.
*/
Package test;
Public class doormain {
Public static void main (string [] ARGs)
{
Doormanager manager = new doormanager ();
Manager. adddoorlistener (New doorlistener1 (); // Add a listener to Gate 1.
Manager. adddoorlistener (New doorlistener2 (); // Add a listener to Gate 2.
// Open the door
Manager. fireWorkspaceOpened ();
System. out. println ("I already come in ");
// Close
Manager. fireWorkspaceClosed ();
}
}
Bytes ----------------------------------------------------------------------------------------------------------------------------
Run DoorMain

Door 1 open
Door 2 open, while opening the corridor light
I already come in.
Door 1 closed
Door 2 close and turn off corridor lights

 

========================================================== ========================================================== ========================

Next, let's take a look at how jdk handles the event mechanism. You can compare it with the custom event above. You will be happy to find that the mechanism is the same.

/** <Br/> * Java swing listener to implement the actionlistener interface. Note the following parameters: (event status class: actionevent) <br/> */<br/> package test; </P> <p> Import Java. AWT. *; <br/> Import Java. AWT. event. *; <br/> Import javax. swing. *; </P> <p> class simplelistener implements actionlistener {<br/>/* <br/> * use this class to listen to events generated by event sources, using the response mechanism <br/> */<br/> Public void actionreceivmed (actionevent e) {<br/> string buttonname = E. getactioncommand (); <br/> If (buttonname. equals ("button 1") <br/> system. out. println ("button 1 clicked "); </P> <p >}< br/>}</P> <p> public class actiontest {<br/> Private Static jframe; // It is defined as a static variable so that main can use <br/> Private Static jpanel mypanel; // This panel is used to place button components <br/> private jbutton button1; // define the button component </P> <p> Public actiontest () {// constructor, create a graphical interface <br/> // create a panel <br/> mypanel = new jpanel (); <br/> // new button <br/> button1 = new jbutton ("button 1 "); // create button 1 <br/> // create an actionlistener and register it with button 1 to respond to the event <br/> simplelistener ourlistener = new simplelistener (); <br/> button1.addactionlistener (ourlistener); <br/> mypanel. add (button1); // Add button to panel </P> <p >}</P> <p> Public static void main (string s []) {<br/> actiontest GUI = new actiontest (); // create a simple1 component </P> <p> frame = new jframe ("simple1 "); // create a jframe <br/> // common method for processing the closing event <br/> frame. addwindowlistener (New windowadapter () {<br/> Public void windowclosing (invalid wevent e) {<br/> system. exit (0); <br/>}< br/>}); </P> <p> frame. getcontentpane (). add (mypanel); <br/> frame. pack (); <br/> frame. setvisible (true); <br/>}</P> <p>
Here, let's take a look at the three roles of the participants of the event mechanism in java:

We have defined a SimpleListener to implement the ActionListener interface,

1. event object: event state object, used in the corresponding methods of listener. With the ActionEvent provided by jdk, we do not need to define it ourselves.

2. event source: the specific event source, which is the button, which registers the specific SimpleListener.

3. event listener: Specifies the listening event class. When it listens to the event

When an object is generated, it calls the corresponding method for processing. Here is our own SimpleListener.

Is it exactly the same mechanism as the custom event above? Yes
Bytes ---------------------------------------------------------------------------------------------------------------------------
Here you may ask why event object does not need to be defined by ourselves? You can think about it. This is a class that indicates "event status change". You can get "Mouse change"

? This seems to be a low-level coding related to the platform. It is impossible for all of them to be flushed and there is no need to be flushed. These jdks have already been implemented for us. Let's take a look at the ActionEvent class.

It inherits java. awt. AWTEvent. the source code of the constructor in this class is as follows:

Static {
/* Ensure that the necessary native libraries are loaded */
Toolkit. loadLibraries ();
If (! GraphicsEnvironment. isHeadless ()){
InitIDs ();
}
}

Let's take a look at the official jdk explanation:

Toolkit is an Abstract superclass for all actual implementations of Abstract Window Toolkit. A subclass of Toolkit is used to bind various components to a specific native Toolkit for implementation. Most applications

The program should not directly call any methods in this class. The Toolkit defines the "binder". The platform-independent classes in the java. awt package are compared with the counterparts in java. awt. peer.

Connect. Some methods defined by Toolkit can directly query the local operating system.

Related Article

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.