Understanding JAVA Event Handling Mechanism from scratch (3)

Posted by lucerias on Mon, 24 Jun 2019 22:28:41 +0200

We have written two sections of teacher-student examples in succession, which must be bored to death. For example, we play 100 times or don't know how to write real code. So, starting with this section, we're starting to move closer to the real code.

The easiest example of an event to understand is the mouse event: we click on the mouse, the mouse sends instructions, and executes code.

 

First: Mouse Click Event Processing Model Basic Edition

At this point, we have to look at the relevant types in JDK. In contrast to the previous section< Understanding JAVA Event Processing Mechanism from scratch (2) > In the UML diagram, we quickly found that the corresponding HomeworkListener, JDK MouseListener, in fact, we can also learn by analysis that MouseListener inherited from EventListener. Now that we have the interface MouseListener, we must have an implementation class, which is assumed to be ConcreteMouseListener. We may wish to achieve 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{%s}A click. MD Itchy to death~~", 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 clicked event handler.

Event Processor: The implementation method of the specific implementation class of the listener is called event processor.

What to look at next, of course, is MouseEvent. MouseEvent, the class in JDK is a little bigger than before. There are a lot of parameters to construct the method, but it doesn't matter. Let's take a look at it slowly. First, I'll say how to use this class, that is, how to new it out.

/*
* Here, the new Component() {} is the event source from event.getSource().
*/
MouseEvent event = new MouseEvent(new Component() {}, 1, 1, 1,2,3,4,false);

In actual and normal circumstances, MouseEvent does not need to own new. JAVA runtime will capture the click action of the hardware mouse, and generate the instance object for us from the bottom of the virtual machine (we will analyze this point below), but at this moment we are first simulating it, so we do not prevent ourselves from scrambling out 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 the source of that event! Look back at where our teacher-student version produced the event:

    public void setHomework(String homework) {
        System.out.printf("%s Homework was arranged%s \n", this.name, homework);
        homeworks.add(homework);
        HomeworkEventObject event = new HomeworkEventObject(this);
        /*
         * In the observer mode, we call notify Observers of Observable directly to notify the observee
         * Now we have to notify ourselves.~~
         */
        for (HomeworkListener listener : homeworkListenerList) {
            listener.update(event, homework);
        }

    }

It's in Teacher's business code setHomework. So where is the new MouseEvent in the current example we're going to write? In our Button business code, who is Button? Button is similar to Teacher, but not exactly the same as Teacher. In Teacher, Teacher itself is the source of events, so this is passed into HomeworkEventObject as a parameter, and Button cannot be passed into MouseEvent as a parameter, because I don't intend to let Button inherit from Component, so we first made a temporary update. Component. OK, when we get to this point, our own Button code will probably come out. It 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(){
        /*
         * Here, the new Component() {} is the event source from event.getSource().
         */
        MouseEvent event = new MouseEvent(new Component() {}, 1, 1, 1,2,3,4,false);
        //event.getSource();
        this.mouseListener.mouseClicked(event);
    }
}

So far, we can draw a clear class diagram. Let's 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 like this:

I was clicked by {com.zuikc.events.Button{[,0,0,0x0,invalid]} and MD itched to death.~~

 

Second, what a normal form program looks like

Above, we try our best to favor the examples of teachers and students, and write the basic version of mouse events, but what about the original program? Come on, let's write a normal program. 99.9% of people write a form program as follows. I know you guys will come up and scold again. What, java, form program? I study JAVA in TMD for EE development, enterprise development. Now, let's talk about how to hurt each other. Even NB, like JAVA, first developed from the form, and JAVA's form framework was overturned and rewritten more than once. So, as you can see from the event of forms, the events of those frameworks in EE are just like cutting cabbage.

Back to the point, 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{%s}A click. MD Itchy to death~~", 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 thing is to create a form, put a button on it, click on it, and execute a line of code. This simple file, with few lines of code, actually implements the functions we implemented in the previous bunch of classes. Come on, let's analyze and point out the listener, event handler, event and event source.

Listener: DemoFrame is a listener, corresponding to ConcreteMouseListener;

Event Processor: The MouseClicked method is the listener, which is also available in ConcreteMouseListener.

Event: I can't see it. What should I do?

Event Source: I can't see it. What should I do?

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

Then, the event and the source of the event are not visible. What should we do at this time? If we look at the output, the output of the code above is:

I was {javax. swing. JButton [, 8,8,80x80, invalid, alignment X = 0.0, alignment Y = 0.0, alignment Y = 0.5, border = javax. swing. plaf. BorderUIResource $CompoundBorderUIResource $CompoundBorderUIResource@7fda7dfe, flags = 296, maximumSize=, minimumSize=, minimumSize=, Size=, defaultIcon=, disabled Icon=, disabled disabled Iconcon, Selected =, margin = javax. preferred. swing. javax. javjavax. swing. prefprefprefprefprefprefprefprefprefiUI InsInsplaf. UI. InsInsleft = 14, bottom = 2, right = 14], paintBorder = true, paintFo Cus = true, pressedIcon=, rollover Enabled = true, rollover Icon=, rollover Selected Icon=, selected Icon=, text = ok, defaultCapable = true]} clicked, and MD itched to death.~~

It looks like the output of the first part of our code above is also a variable generated during the running of JButton business code, but we don't know where and where it was generated. But that's OK. Let's look at the debugging stack!

Step by step, we finally got here:

 

So, MouseEvent is also new in the business code, so you might want to say, what about target, the first important parameter? Target is also an important source of events. The reason is very simple. Continue to catch up, limited to the length of the article. It's not here. It's new out somewhere you want to see it.

Now let's fill in the answer.

Events: JAVA runtime captures hardware mouse triggers, thus calling the event handler. The MouseEvent generated within the event handler is the event.

Event source: JAVA runtime captures the trigger of hardware mouse, which calls the event handler. The target generated within the event handler is the event source.

 

Three: Normal version of the first part of the above code

According to the code of No. 2 Middle School, what should the code of the first part look like?

Comparing one and two together, as long as two places are changed, the code of one middle school is exactly the same as that of the second middle school.

1: Name ConcreteMouseListener DemoFrame;

2: Place Button instance from client to ConcreteMouseListener;

OK, that's how simple things are.

The first and second parts of the series are:

1: Understanding JAVA Event Processing Mechanism from scratch (1)

2: Understanding JAVA Event Processing Mechanism from scratch (2)

Topics: Java JDK