Explanation of Java event handling steps

  • 2021-06-28 12:46:04
  • OfStack

What is an event?

A user's action on a component is called an event.

Event source: An GUI component object capable of generating events. Event Processing: A method that accepts, parses, and processes event class objects to achieve user interaction. Event listener: A class that can handle events.

Processing event steps:

Assume the event is XXXX

1. Register an event listener object for an event to the event source


addXXXXListener(...);

2. Event listeners designed to handle such events


class  Class name  implements XXXXListener{
 Rewrite XXXXListener Methods in interfaces 
}

Explain:

To design a listener that can handle XXXX events, you only need to write a class that implements the XXXXListener interface, because the XXXXListener interface already defines a method for handling XXXX events.

eg:


import java.awt.*;
import java.awt.event.*;
class A implements ActionListener{
public void actionPerformed(ActionEvent e){// Click Event 
System.out.println("haha");
}
}
public class text{
public static void main(String[] args){
Frame f=new Frame();
Button bn=new Button("ok");
f.add(bn);
A aa =new A();
bn.addActionListener(aa);
f.pack();// Show content height and width only 
f.setVisible(true);
 }
}

What are the events:

ActionEvent: Events that occur when a component is activated KeyEvent: Events occurring while operating the keyboard MouseEvent: Occurs when the mouse is operated WindowsEvent: Events that occur when a window is manipulated

summary


Related articles: