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.
(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;
}
}
(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 ");
}
}
}
(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.
/**
* Event source object. Here you can think of it as a remote control that controls the opening and closing of the door,
* (If it is in swing, it is similar to a button)
*/
Package test;
Import java. util .*;
Public class doormanager {
Private collection listeners;
/**
* Add events
* @ Param listener doorlistener
*/
Public void adddoorlistener (doorlistener listener ){
If (listeners = NULL ){
Listeners = new hashset ();
}
Listeners. Add (listener );
}
/**
* Remove an event
* @ Param listener doorlistener
*/
Public void removedoorlistener (doorlistener listener ){
If (listeners = NULL)
Return;
Listeners. Remove (listener );
}
/**
* The Door Opening event is triggered.
*/
Protected void fireworkspaceopened (){
If (listeners = NULL)
Return;
Doorevent event = new doorevent (this, "open ");
Notifylisteners (event );
}
/**
* Close event triggering
*/
Protected void fireworkspaceclosed (){
If (listeners = NULL)
Return;
Doorevent event = new doorevent (this, "close ");
Notifylisteners (event );
}
/**
* Notify all doorlistener
*/
Private void policylisteners (doorevent event ){
Iterator iter = listeners. iterator ();
While (ITER. hasnext ()){
Doorlistener listener = (doorlistener) ITER. Next ();
Listener. doorevent (event );
}
}
}
(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 ();
}
}
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.
/**
* Java swing listener implements the actionlistener interface. Note the following parameters: (event status class: actionevent)
*
*/
Package test;
Import java. AWT .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Class simplelistener implements actionlistener {
/*
* This class is used to listen to events generated by event sources and the response mechanism is used.
*/
Public void actionreceivmed (actionevent e ){
String buttonname = E. getactioncommand ();
If (buttonname. Equals ("button 1 "))
System. Out. println ("button 1 clicked ");
}
}
Public class actiontest {
Private Static jframe frame; // It is defined as a static variable for main to use.
Private Static jpanel mypanel; // This panel is used to place button Components
Private jbutton button1; // define the button component here
Public actiontest () {// constructor to create a graphical interface
// Create a panel
Mypanel = new jpanel ();
// Create button
Button1 = new jbutton ("button 1"); // create button 1
// Create an actionlistener and register it with button 1 to respond to the event
Simplelistener ourlistener = new simplelistener ();
Button1.addactionlistener (ourlistener );
Mypanel. Add (button1); // Add button to panel
}
Public static void main (string s []) {
Actiontest GUI = new actiontest (); // creates a simple1 component.
Frame = new jframe ("simple1"); // create a jframe
// The usual method for processing the Close event
Frame. addwindowlistener (New windowadapter (){
Public void windowclosing (windowevent e ){
System. Exit (0 );
}
});
Frame. getcontentpane (). Add (mypanel );
Frame. Pack ();
Frame. setvisible (true );
}
}
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". Can you throw "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. The actionevent class inherits java. AWT. awtevent. The source code of 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 should not directly call any method in this class. The toolkit defines a "binder" that connects platform-independent classes in the Java. AWT package with the counterparts in Java. AWT. Peer. Some methods defined by Toolkit can directly query the local operating system.
Reproduced from: http://dev.10086.cn/cmdn/wiki/index.php? Doc-view-4230.html