Understanding Java event handling mechanism from scratch (3)

Source: Internet
Author: User
Tags stub

We have written two sections of the teacher-student example, must feel bored to death, such an example we are playing 100 times, or do not know how to write the real code. From this section, we begin to move closer to the real code.

The most understandable example of an event is a mouse event: We click the mouse, the mouse sends instructions, executes the code.

One: mouse click event Processing Model Basic version

At this point, we have to look at the related types in the JDK. According to the UML diagram in the previous section, "Understanding Java event handling mechanism from scratch (2)", we quickly found that there are mouselistener in correspondence homeworklistener,jdk, we can tell by analysis, MouseListener inherits from EventListener. Now that we have the interface MouseListener, we must have an implementation class, which is called: Concretemouselistener. You might want to do it first:

Package com.zuikc.events;

Import java.awt.event.MouseEvent;
Import Java.awt.event.MouseListener;

public class Concretemouselistener implements MouseListener {

Public Concretemouselistener () {

}
@Override
public void mouseclicked (MouseEvent e) {
System.out.printf ("I got a bit of {%s}, MD itches dead ~ ~", E.getsource (). toString ());
}

@Override
public void mousepressed (MouseEvent e) {
TODO auto-generated Method Stub
}

@Override
public void mousereleased (MouseEvent e) {
TODO auto-generated Method Stub
}

@Override
public void mouseentered (MouseEvent e) {
TODO auto-generated Method Stub
}

@Override
public void mouseexited (MouseEvent e) {
TODO auto-generated Method Stub
}

}

We add business code for the event handler that we clicked.

Event handler: the implementation of the specific implementation class of the listener is called the event handler.

What to see next, of course, is mouseevent. MouseEvent, the class in this JDK is relatively, a little bit large, the parameters of the construction method a bit more, but no matter, we look slowly, I first say this class how to use, that is how new out.

/*
* Here the new Component () {} is the source of event sources Event.getsource ()
*/
MouseEvent event = new MouseEvent (new Component () {}, 1, 1, 1,2,3,4,false);

In practical and normal circumstances, MouseEvent is not necessary for its own new, the Java runtime will capture the hardware mouse click action, the virtual machine from the bottom for us to generate the instance object (the following will be analyzed for us), but we are at this moment we are simulation ah, So it doesn't prevent us from being random and new. Note that new is not a problem, the key to the problem is that we have to know the meaning of its constructor parameters, and the core key parameter is the first parameter, new Component (), what is this? This is the source of the event! Look back at where our teacher student version is producing events:

    public void sethomework (String homework) {
         System.out.printf ("%s assigned job%s \ n", this.name, homework);
        Homeworks.add (homework);
        Homeworkeventobject event = new Homeworkeventobject (this);
       /*
         * in observer mode, We call observable's notifyobservers directly to notify the Observer
         * Now we can only notify ourselves ~ ~
         */
        for ( Homeworklistener listener:homeworklistenerlist) {
             Listener.update (event, homework);
       }

   }

is in the business code sethomework of teacher. So, in the current example of what we're going to write, where is new mouseevent? We are in the button's business code, who is the button, the button is similar to teacher, but not exactly the same as teacher, in teacher, teacher itself is the event source, So it passed into the homeworkeventobject as a parameter, and the button cannot be passed in as a parameter into MouseEvent, because I'm not going to let the button inherit from component, So we first new a temporary component. OK, the analysis here, our own button code is probably out, this looks like:

Package com.zuikc.events;

Import java.awt.AWTEvent;
Import Java.awt.AWTEventMulticaster;
Import java.awt.Component;
Import java.awt.event.MouseEvent;
Import Java.awt.event.MouseListener;
Import Java.awt.peer.LightweightPeer;

public class Button {
Private MouseListener MouseListener;
public void Addmouselistener (MouseListener l) {
MouseListener = l;
}
public void DoClick () {
/*
* Here the new Component () {} is the source of event sources Event.getsource ()
*/
MouseEvent event = new MouseEvent (new Component () {}, 1, 1, 1,2,3,4,false);
Event.getsource ();
This.mouseListener.mouseClicked (event);
}
}

At this point, we can draw a clear class diagram, to see:

By the way, let's look at the client-side code:

public static void Main (string[] args) {
Concretemouselistener listener = new Concretemouselistener ();
Button button = New button ();
Button.addmouselistener (listener);
Button.doclick ();
}

Run it, you should get an output similar to this:

I was {Com.zuikc.events.button$1[,0,0,0x0,invalid]} a bit, MD itch dead ~ ~

Two, the appearance of a normal form program

Above, we try to favor the example of teacher students, write out the basic version of the mouse event, but the good program is the way it is? Come on, let's write a normal program, 99.9% is written as follows when a person is writing a form program. I know you guys are going to yell, what, Java, form programs? I am a TMD to learn Java for the development of EE, enterprise development. Now, we say that we do not hurt each other, you know, even NB, like Java, is the first to start from the form, and, Java's form framework has been rewritten more than once. So, the events of the form you see, the events of the frames in the EE are just like the cut cabbage.

Anyway, look at the code:

Package com.zuikc.events;

Import java.awt.event.MouseEvent;
Import Java.awt.event.MouseListener;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;

public class Client {
public static void Main (string[] args) {
New Demoframe ();
}
}

Class Demoframe extends JFrame implements MouseListener {

Public Demoframe () {
Super ("Demo");
This.setsize (500, 400);
This.setlocationrelativeto (NULL);
This.getcontentpane (). setlayout (NULL);
This.setvisible (TRUE);

JButton button1 = new JButton ("OK");
Button1.setbounds (8, 8, 80, 80);
Button1.addmouselistener (this);
This.getcontentpane (). Add (button1);
}

@Override
public void mouseclicked (MouseEvent e) {
System.out.printf ("I got a bit of {%s}, MD itches dead ~ ~", E.getsource (). toString ());
}

@Override
public void mousepressed (MouseEvent e) {
}

@Override
public void mousereleased (MouseEvent e) {
}

@Override
public void mouseentered (MouseEvent e) {
}

@Override
public void mouseexited (MouseEvent e) {
}
}

What does this piece of code mean? The simplest thing is to create a form where a button is placed and a line of code is executed after the click. This simple file, with few lines of code, actually implements the functionality we implemented in a bunch of classes above. Come on, let's analyze the listener, event handler, event, event source.

Listener: Demoframe is the listener, corresponding to Concretemouselistener;

Event handler: Mouseclicked method is the listener, Concretemouselistener inside also have this method;

Event: Can't see, what to do?

Event Source: Can't see, what to do?

Note that the form itself is the listener, so how do I add a listener to the button in the preceding code? Button1.addmouselistener (this); Yes, just add yourself.

Then, the event and event sources are not visible, what should I do? If we look at the output, the output of the above code is:

I was {javax.swing.jbutton[,8,8,80x80,invalid,alignmentx=0.0,alignmenty=0.5,bo[email protected]7fda7dfe,flags=296, maximumsize=,minimumsize=,preferredsize=,defaulticon=,disabledicon=,disabledselectedicon=,margin= Javax.swing.plaf.insetsuiresource[top=2,left=14,bottom=2,right=14],paintborder=true,paintfocus=true, pressedicon=,rolloverenabled=true,rollovericon=,rolloverselectedicon=,selectedicon=,text=ok,defaultcapable= True]} A bit, MD itch dead ~ ~

It looks like the output from the first part of our code above is also a variable generated during the run of the JButton business code, but where it is generated and where it is generated, we don't know. But it doesn't matter, let's look at the debug stack!

Step by step up the chase, we finally caught up here:

Thus, MouseEvent is also in the business code new out, you may want to, that this important first parameter target? Target is also very important, the reason is very simple, continue to chase, confined to space, here is not unfolding, it is in a place where you want to see it was new.

Now we answer,

Event: The Java runtime captures the hardware mouse trigger, which invokes the event handler, and the mouseevent generated inside the event handler is the event;

Event Source: The Java runtime captures the hardware mouse trigger, which invokes the event handler, and the target generated inside the event handler is the source of the event;

Third: Normal version of the first part of the code

According to the code in the two, what should our first part of the code look like?

One and two in a comparison, in fact, as long as two places, one of the code and the two are exactly the same,

1: Name Concretemouselistener as Demoframe;

2: The button instance is placed inside the Concretemouselistener by the client;

OK, the event is so simple.

The first and second parts of the series were:

1: Understanding Java event handling mechanism from scratch (1)

2: Understanding Java event handling mechanism from scratch (2)

Understanding Java event handling mechanism from scratch (3)

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.