Java implements event monitoring through interfaces

Preface:
Through the last article, we learned how to implement an interface and implement it. After understanding the principle, we are equivalent to having a key. The next thing we have to do is to open some of the treasure interfaces that have been written in Java itself!

1. What is monitoring?
Answer: To put it bluntly, it means to let the computer recognize some actions, such as "click the mouse", "click the carriage return", "close the window"...

2. What is the relationship between monitoring and interface?
Answer: When I first learned programming, I was thinking about how to perform a human-computer interaction. For example, how can a computer recognize my "clicking the mouse" action?
The computer monitors the user's actions and performs certain operations, and then I further decide my next action based on the results of the operation. This is a simple interactive process.
Then we can simply think about it, it is quite difficult to write such interactive code from the bottom every time, and it is highly repetitive, time-consuming and laborious.
Fortunately, Java already has an interface for writing a well-written framework for such an action monitoring process, and you can just fetch it when you want to use it, for example:

ActionListener
MouseListener
。。。。。。。

We implement the corresponding monitoring interface and give specific behaviors to achieve the effect of what the computer does under a certain action!

3. Realize the "mouse click" monitoring
step1: create a monitoring class will report an error as shown in the figure
Insert picture description here
step2: right-click this interface and press F3 to open the definition,
Insert picture description here
copy the selected part and change it; change it to {} Insert picture description here
here and you can write what you want to achieve Content! Insert picture description here
4. Example
step1. Create the main file demo and interface Click_Listener Insert picture description here
step2. Click_Listener

public class Click_Listener implements ActionListener {
    
    
 
 @Override
  public void actionPerformed(ActionEvent e) {
    
    
   String btn=e.getActionCommand();
   System.out.println(btn+"被点击了");
  }
}

step3.demo

Click_Listener ui=new Click_Listener();//创建监听的对象


btni.addActionListener(ui);//添加监听

step4. Running results
Insert picture description here

Guess you like

Origin blog.csdn.net/Lamont_/article/details/109520325