Home  >  Article  >  Java  >  Detailed explanation of JAVA event processing mechanism

Detailed explanation of JAVA event processing mechanism

零下一度
零下一度Original
2017-06-25 10:38:392142browse

We wrote two sections of teacher-student examples in a row, and we must have felt bored to death. Even if we played this example 100 times, we still don’t know how to write real code. Starting from this section, we start to move closer to the real code.

The easiest example of an event is a mouse event: when we click the mouse, the mouse sends instructions to execute the code.

1: Basic version of mouse click event processing model

At this time, we must check the related types in the JDK. Comparing the UML diagram in the previous section "Understanding JAVA Event Processing Mechanism from Scratch (2)", we quickly discovered that corresponding to HomeworkListener, there is MouseListener in JDK. In fact, we can also know through analysis that MouseListener inherits from EventListener. Now that we have the interface MouseListener, we must have an implementation class. This class is assumed to be called: ConcreteMouseListener. You might as well implement 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 was clicked by {%s}, MD was itchy~~", e.getSource().toString());
}

@Override
public void mousePressed(MouseEvent e) {
                                                                            using using use using use using using using using using using using using using using     out out out out out out out out out Out out '''' ’ ‐ ’ ’s stub
      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 click event handler .

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

What to look at next, of course, is MouseEvent. MouseEvent, this class in the JDK is relatively large, and the constructor method has a lot of parameters, but it doesn't matter. Let's take a look at it. I'll first talk about how to use this class, that is, how to create it new.

/*

* The new Component() {} here is the event source obtained by event.getSource()

*/
MouseEvent event = new MouseEvent(new Component () {}, 1, 1, 1,2,3,4,false);



In actual and normal circumstances, there is no need for MouseEvent to be new by itself, it will be captured when JAVA is running For the click action of the hardware mouse, the instance object is generated for us by the bottom layer of the virtual machine (this will be analyzed for us below), but we are simulating it at this moment, so it does not prevent us from randomly creating a new one. Note that new is not a problem. The key to the problem is that we must know the meaning of its constructor parameters, and the core key parameter is the first parameter, new Component(). What is this? This is that event source! Let’s look back at where our teacher-student version produces events:

public void setHomework(String homework) {

System.out.printf("%s assigned homework %s \ n", this.name, homework);

homeworks.add(homework);
HomeworkEventObject event = new HomeworkEventObject(this);

/*
* In observer mode, we call it directly Observable's notifyObservers to notify the observed
* Now we can only notify ourselves~~
*/
for (HomeworkListener listener: homeworkListenerList) {
listener.update(event, homework);
}

}

is in Teacher’s business code setHomework. So, in the current example we are going to write, where is the new MouseEvent? In the business code of Button, who is Button? Button is similar to Teacher, but not exactly the same as Teacher. In Teacher, Teacher itself is the event source, so this is passed into HomeworkEventObject as a parameter, and Button cannot be used as a parameter. The parameters are passed into MouseEvent. Because I don't want Button to inherit from Component, we first create a new temporary Component. OK, after the analysis, our own Button code probably came out, which looks like this:

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 () {
/ *
*The new component () {} here is the event source of event.getsource (). {}, 1, 1, 1,2,3,4,false);
//event.getSource();
this.mouseListener.mouseClicked(event);
}
}

At this point, we can draw a clear class diagram, let’s take a look:

Detailed explanation of JAVA event processing mechanismBy the way, let’s take a look at the client 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]} clicked, MD was itchy to death~~

Second, what a normal form program looks like

Above, we tried our best to focus on the examples of teachers and students, and wrote the basic version of mouse events, but what about the original appearance of the program? Come on, let's write a normal program next. 99.9% of people write it like this when they write a form program. I know some of you will come up and scold me again, what, java, form program? I fucking learned JAVA for EE development and enterprise development. Now, let's first talk about whether we should hurt each other. You must know that even NB such as JAVA first made its fortune from forms. Moreover, JAVA's form framework has been overthrown and rewritten more than once. So, you understand the events of the form, and the events of the framework in EE are just like chopping cabbage.

Back to business, 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 was clicked by {%s}, MD was itchy~~ ", 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 code mean? The simplest is to create a form, place a button on the form, and when clicked, a line of code is executed. This simple file, with not many lines of code, actually implements the functions implemented in a bunch of classes above. Come on, let's analyze it and point out the listeners, event handlers, events, and event sources.

Listener: DemoFrame is the listener, corresponding to ConcreteMouseListener;

Event handler: The MouseClicked method is the listener, and ConcreteMouseListener also has this method;

Event: I can’t see it anymore, what should I do?

Event source: I can’t see it, what should I do?

Note that the form itself has a listener, so how to add a listener to the button in the above code? button1.addMouseListener(this); Yes, just add yourself.

Then, the event and the event source are no longer visible. What should I do at this time? 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,border=javax.swing .plaf.BorderUIResource$CompoundBorderUIResource@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]} Clicked and MD was itchy~ ~

It seems that the output similar to the first part of our code above is also a variable generated during the running of the JButton business code, but we do not know where it is generated or where it is generated. But that’s okay, let’s look at the debug stack!

Chasing up step by step, we finally got here:

Detailed explanation of JAVA event processing mechanism

It can be seen that MouseEvent is also in the business code When new comes out, you may be wondering, what about this important first parameter, target? Target, but the event source is also very important. The reason is very simple. Keep going up. Due to space limitations, we will not expand it here. It is new in a place where you want to see it.

Now we complete the answer,

Event: JAVA captures the hardware mouse trigger when running, thus calling the event processor. The MouseEvent generated inside the event processor is Event;

Event source: The JAVA runtime captures the hardware mouse trigger, thus calling the event processor. The target generated inside the event processor is the event source;

3: The normal version of the first part of the code above

Written according to the code in the second part, what should our first part of the code look like?

Compare one and two together. In fact, as long as two places are changed, the code in one is completely consistent with that in two.

1: Name ConcreteMouseListener DemoFrame;

2: Place the Button instance from the client into the ConcreteMouseListener;

OK, the event is that simple.

The first and second parts of this series are respectively:

1: Understand the JAVA event processing mechanism from scratch (1)

2: Understand JAVA from scratch Event handling mechanism (2)

The above is the detailed content of Detailed explanation of JAVA event processing mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn