Home  >  Article  >  What behaviors can objects recognize and respond to?

What behaviors can objects recognize and respond to?

青灯夜游
青灯夜游Original
2020-08-29 11:32:594615browse

The behavior that an object can recognize and respond to is an "event". Behaviors that an object can recognize and respond to are called events. Events are actions that an object can recognize and detect. When this action occurs on an object, its corresponding event will be triggered.

What behaviors can objects recognize and respond to?

Java event summary

Event processing model

For GUI applications, event processing is essential, so we need to master the event processing model proficiently. For events we need to understand two terms: event source object and listener object. We can get a rough idea from the literal meaning. Let’s explain the system below:

  • The listener object is an instance of a class that implements a specific listener interface

  • The event source is an object that can register listener objects and send event objects

  • When an event occurs, the event source passes the event object to all registrations The listener

  • The listener object will use the information in the event object to decide how to respond to the event

First we will the listener object Register with the event source object so that when the event is triggered, the system can access the corresponding listener through the event source. As shown below:

What behaviors can objects recognize and respond to?

#When the event source triggers an event, the system encapsulates the relevant information of the event into an event object of the corresponding type and sends it to the event source registered to the event source. Corresponding listener. As shown below:

What behaviors can objects recognize and respond to?

#When the event object is sent to the listener, the system calls the corresponding event processing method of the listener to process the event, that is, to respond. As shown below:

What behaviors can objects recognize and respond to?

#Note: There is a "many-to-many" relationship between the listener and the event source.

The hierarchy of event objects

The highest level in the event object is java.util.EventObject, the root class from which all event status objects will be derived. In addition to the classes inherited from the Object class, this class also has the getSource() method, whose function is to return the object where the Event originally occurred.

Except this class is in the util package, the others are in the java.awt, java.awt.event package or java.swing, java.swing.event package. It is worth noting that it does not mean the Swing control. Only use Swing events.

The AWTEvent class provides the getID() method to return the identifier of the event nature. For example, if a mouse event occurs, you can find out whether it was a click, drag, press, or other operation.

Description of several commonly used event classes:

  • EventObject: the super class of all event classes. The most important method - getSource(), returns the object that generated an event

  • AWTEvent: the super class of all AWT event classes. The most important method - getID(), returns the ID number of an event. The event ID is an integer, which specifies the type of event, such as a button event or a mouse click event

  • ##ActionEvent : Events that occur when a component is activated

  • AdjustmentEvent: Events that occur when an adjustable component (such as moving a scroll bar) is adjusted

  • ComponentEvent: A high-level event that occurs when manipulating a component

  • ContainerEvent: occurs when a component is added or removed from a container

  • InputEvent: generated by an input device A high-level event

  • ItemEvent: Occurs when selecting from a selection item, check box or list

  • KeyEvent: Occurs when operating the keyboard

  • MouseEvent: Occurs when operating the mouse

  • PaintEvent: An event occurs when drawing a component

  • TextEvent: Occurs when the text is changed

  • WindowEvent: An event occurs when the window is manipulated, such as maximizing or minimizing a window.

The hierarchy of listener objects

The listener object is an instance of a class that implements a specific listener interface, then the listener interface That's what we're concerned about. The top-level interface in the listener interface is java.util.EventListener. This interface is the mark interface that all event listener interfaces must extend. What is surprising is that this interface is completely empty. There is no definition of any abstract method in it. When I check the source code, it is empty!

  • The event listener class (the class to which the listener object belongs) must implement the event listener interface or inherit the event listener adapter class.

  • The event listener interface defines the methods that must be implemented to handle events.

  • The event listener adapter class is a simple implementation of the event listener interface. The purpose is to reduce the workload of programming.

The event listener interface naming method is: XXListener, and in java, these interfaces have already been defined. Used to be implemented, it defines the event handler (that is, the event handling method prototype, this method needs to be reimplemented).

For example: ActionListener interface, MouseListener interface, WindowListener interface, KeyListener interface, ItemListener interface, MouseMotionListener interface, FocusListener interface, ComponentListener interface, etc.

Event source

Events are initially generated by an event source. The event source can be a GUI component Java Bean or an object capable of generating events. In the case of a GUI component, the event source or a peer of the component (for Abstract Window Toolkit [awt] GUI components) say) or the component itself (for Swing components).

In java, what kind of events each component will generate has been defined. In other words, for any event, it is already determined which components can produce it.

Events

AWT divides events into low-level events and semantic events.

  • Semantic events are events that represent user actions.

  • Low-level events are the events that form those events.

Common semantic event classes in the java.awt.event package:

  • ActionEvent (corresponding to button click, menu selection, selection list item or ENTER in the text box)

  • AdjustmentEvent (the user adjusts the scroll bar)

  • ItemEvent (the user selects an item from a check box or list box Item)

Five commonly used low-level event classes:

  • KeyEvent (a key is pressed or released)

  • MouseEvent (mouse button is pressed, released, moved or dragged)

  • MouseWheelEvent (mouse wheel is turned)

  • FocusEvent (a component gains or loses focus)

  • WindowEvent (the window state is changed)

java.awt.event package Commonly used event adapter classes defined in include the following:

 1. ComponentAdapter(Component Adapter)

 2. ContainerAdapter(Container Adapter)

 3. FocusAdapter(Focus Adapter)

 4. KeyAdapter(Keyboard Adapter)

 5. MouseAdapter(Mouse Adapter)

 6. MouseMotionAdapter(Mouse Motion Adapter)

 7. WindowAdapter(Window Adapter)

Corresponding relationship between event source and listener

The following figure is the corresponding relationship diagram in actual Java development:

What behaviors can objects recognize and respond to?

Common event objects and listener interface comparison table:

What behaviors can objects recognize and respond to?

##ActionListenerAbstractButtonAdjustmentListenerJscrollBarItemListenerAbstractButtonFocusListenerComponent##KeyListenerMouseListenerMouseMotionListenerMouseWheelListenerWindowListenerWindowFocusListenerWindowStateListener

Suggestion: To understand this part, you need to first understand the general relationship between Java visual components and containers, which will facilitate our understanding.

Usual program development steps

As a program developer, what we have to do is to create an event listener object and place it in the component where the event is activated (new) To register. The so-called creation of an event listener object means creating a class, and this class must implement an interface in the form of XXListener (or inherit "a class that has implemented XXListener"). Of course, implementing this interface means overriding the method of XXListener.

For example, for ActionListener, there is only one actionPerformed method:

class B1 implements ActionListener{// 实现ActionListener
    @override
    public void actionPerformed(ActionEvent e){
	//重写actionPerformed     
        //do somthing....
    }
}

Register the event listener in the component of the activated event: that is, call a method in the form addXXListener().

For example:

Button b1 = new Button("Button 1");
b1.addActionListener(new B1()); //注册事件监听器

b1 is the component of the activated event. In this way, when the event is activated, the processing flow is as follows: Since the event listener has been registered through addActionListener, so, The specific event handling method, namely the actionPerformed() function, will be called. In this way, the execution result depends on what actionPerformed does specifically.

A listener only listens to a specific event source, then we can use anonymous objects to register the listener.

For example:

JButton b=new JButton("jjjj");
b.addActionListener(new ActionListener() {
	@Override
	public void actionPerformed(ActionEvent e) {
		//重写actionPerformed     
        //do somthing....
	}
});

The general steps for processing each component event in Java Swing are:
 1. Create a new component (such as JButton).
 2. Add the component to the corresponding panel (such as JPanel).
 3. Register a listener to listen for events generated by the event source (such as responding to the user clicking a button through ActionListener).
 4. Define the method to handle the event (such as defining the corresponding method in actionPerformed in ActionListener).

The first way to create a listener class above can be an inner class, and the second way to create a listener is an anonymous inner class, which is easy to understand.

Separation design of response and interface

We write event processing and interface together. One is inconvenient to maintain, and the other will cause the current code file to be bloated. Therefore, I still suggest that you separate the corresponding events from the interface, which can not only make up for the first two defects, but also improve the reusability of the code. But don’t ignore the use of inner classes and anonymous inner classes, because each has its own advantages and disadvantages, and we must consider them comprehensively.

Swing package provides a very practical mechanism to encapsulate commands and connect them to multiple event sources, which is the Action interface. An action is an object that encapsulates the following:

  • Description of the command (a text string and an optional icon)

  • Execute the command Required parameters (for example, the color requested to be changed in the example listed)

Please refer to the API for details.

It should be noted that Action is an interface, not a class. All classes that implement this interface must implement 7 of the methods. Fortunately, there is a class that implements all methods of this interface except the actionPerformed method, which is AbstractAction. This class stores all name/value pairs and manages property change listeners. We can directly extend the AbstractAction class and implement the actionPerformed method in the extended class.

A better design method I have seen is: the listener class inherits javax.swing.AbstractAction, and the component is passed to the listener when registering on the component.

Listener:

public class AC_temp extends AbstractAction{
	private static final long serialVersionUID = 1L;
	MainFrame main;
	public AC_EditVideoInfo(MainFrame temp,Color color) {
		main=temp;
		putValue(Action.NAME, "name");
		putValue(Action.SMALL_ICON, new ImageIcon("images/edit.png"));
		putValue(Action.SHORT_DESCRIPTION, "description");
                putValue("color",color);
                //....
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// do something
	}
}

Event source:

组件.addActionListener(new AC_EditVideoInfo(this));//注册监听器

Create a listener that contains a method call

java.beans. EventHandler is an event manager from the naming point of view. The explanation given by the official API is: The EventHandler class provides support for dynamically generating event listeners. The methods of these listeners execute a simple statement involving the incoming event object and the target object.

For a more detailed explanation, refer to:————————>>>>>>>>>

Example of using EventHandler:

The simplest way to use EventHandler is to install a listener and call a method on the target object without parameters. In the following example, an ActionListener is created that calls the toFront method on a javax.swing.JFrame instance.

myButton.addActionListener(
    (ActionListener)EventHandler.create(ActionListener.class, frame, "toFront"));

When myButton is pressed, the frame.toFront() statement will be executed. By defining a new implementation of the ActionListener interface and adding its instance to the button, the user can achieve the same effect, with additional compile-time type safety:

//Equivalent code using an inner class instead of EventHandler.
myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        frame.toFront();
    }
});

The other simplest use of EventHandler is from the listener Extracts the property value from the first parameter of the method in the listener interface (usually an event object) and uses it to set the property value in the target object. In the following example, an ActionListener is created that sets the nextFocusableComponent property of the target (myButton) object to the value of the event's "source" property.

EventHandler.create(ActionListener.class, myButton, "nextFocusableComponent", "source")

This would correspond to the following inner class implementation:

//Equivalent code using an inner class instead of EventHandler.
new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        myButton.setNextFocusableComponent((Component)e.getSource()); 
    }
}

It is also possible to create an EventHandler that just passes the incoming event object to the target action. If the fourth parameter in EventHandler.create is an empty string, the event is delivered as follows:

EventHandler.create(ActionListener.class, target, "doActionEvent", "")

This will correspond to the following inner class implementation:

//Equivalent code using an inner class instead of EventHandler.
new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        target.doActionEvent(e);
    }
}

EventHandler 最常见的用法可能是从事件对象的 source 中提取属性值,并将此值设置为目标对象的属性值。在以下示例中,将创建一个 ActionListener,它将目标对象的 "label" 属性设置为事件源的 "text" 属性的值("source" 属性的值)。

EventHandler.create(ActionListener.class, myButton, "label", "source.text")

这将对应于以下内部类实现:

//Equivalent code using an inner class instead of EventHandler.
new ActionListener {
    public void actionPerformed(ActionEvent e) {
        myButton.setLabel(((JTextField)e.getSource()).getText()); 
    }
}

可以使用以 "." 字符分隔的任意数量的属性前缀来“限定”事件属性。采用出现在 "." 字符前面的“限定”名称作为将应用于事件对象的属性名称,最左边的最先应用。
例如,以下动作侦听器

EventHandler.create(ActionListener.class, target, "a", "b.c.d")

可以写成以下内部类(假定所有属性都有规范的获取方法并返回适当的类型):

//Equivalent code using an inner class instead of EventHandler.
new ActionListener {
    public void actionPerformed(ActionEvent e) {
        target.setA(e.getB().getC().isD()); 
    }
}

也可以使用以 "." 字符分隔的任意数量的属性前缀来“限定”目标属性。例如,以下动作侦听器:

EventHandler.create(ActionListener.class, target, "a.b", "c.d")

可以写成以下内部类(假定所有属性都有规范的获取方法并返回适当的类型):

//Equivalent code using an inner class instead of EventHandler.
   new ActionListener {
     public void actionPerformed(ActionEvent e) {
         target.getA().setB(e.getC().isD()); 
    }
}

由于 EventHandler 最终依赖反射来调用方法,所以建议不要以重载方法为目标。例如,如果目标是类 MyTarget 的一个实例,而 MyTarget 定义如下:

public class MyTarget {
     public void doIt(String);
     public void doIt(Object);
   }

那么方法 doIt 被重载。EventHandler 将基于源调用恰当的方法。如果源为 null,那么两个方法都可以,具体调用哪个方法是不确定的。因此,建议不要以重载方法为目标。

更多相关知识,请访问:PHP中文网

Common event source and listener interface comparison table
Listener interface Event source
JcomboBox
JTextField
Timer
JComboBox
Component
Component
Component
Component
Window
Window
Window

The above is the detailed content of What behaviors can objects recognize and respond to?. 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