Home > Java > JavaBase > body text

Detailed explanation of events in java with pictures and texts

Release: 2019-11-28 17:35:00
forward
2356 people have browsed it

Detailed explanation of events in java with pictures and texts

Before learning java events, you must have a certain understanding of java internal classes, common java components, containers, layout managers, and java abstract window toolkit. Combined with the following knowledge points, You can do some simple window programs. (Recommended: java video tutorial)

The Java language uses the authorization event model to process events. Under this model, each component has corresponding events, such as a click event for a button, a content change event for a text field, etc.

When an event is triggered, the component will send the event to each event listener registered by the component. The event listener defines the processing of events corresponding to different events. At this time, the event listener The processor will call different event handlers based on different event information to complete the processing of this event. The event information will be received only after the event listener is triggered.

The salient feature of this model is that when the component is triggered, it does not process it itself, but leaves the processing operation to a third party to complete. For example, when a button is clicked in the GUI, the button is an event source object. The button itself has no right to react to this click. What it does is send information to its registered listener (event processing (or, in essence, it is also a class) to handle.

To understand Java's event processing, you must understand the following three important summaries.

(1), Event - event generated by user operation

(2), Event source Event source - component that generates event

(3), Event handling method Event handle - method of handling events

1. Basic principles of event processing

When an event is triggered on a button, the virtual machine generates a click The event object is then searched for the registered related processing method on the button, that is, the event source, and the event object is passed to this method, and this method is executed.

Sample program:

In the following program, JButton jb is the event source, ClickAction is the event handler, jb.addActionListener(a); associates the event source with the event handler. When a click event occurs on the event source, the code defined in ClickAction is executed.

The source code is as follows:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class EventTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("示例程序1");
        //1、事件源jb按钮就是事件源,因为要点击它
        JButton jb = new JButton("click");
        //2、事件处理程序ClickAction表示事件处理程序
        ClickAction a = new ClickAction();
        //3、关联,将事件源和事件处理程序a关联起来,意思是发生点击执行a
        jb.addActionListener(a);
        //将jb源事件添加到窗口中。
        j.getContentPane().add(jb);
        j.pack();
        j.setVisible(true);
    }
}

//事件处理程序,点击就是一个Action事件
class ClickAction implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        System.out.println("hello");
    }
}
Copy after login

2. Event object

In your example above, ActionEvent is an event object. This event is generated by JButton when the JButton is pressed. The event is passed to the ActionListener object registered by registering the listener, through which the most common information such as the time when the event occurs and the event source when the event occurs can be obtained.

Common methods of ActionEvent are as follows:

(1)String getActionCommand(): Returns the command string related to this type of action. The default component is title.

(2)int getModifiers(): Returns the keyboard button pressed simultaneously when this action occurs

(3)long getWhen(): Returns the long form of the event when this event occurs.

Sample program:
The source code is as follows:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class EventTest2 {

    public static void main(String[] args) {

        JFrame j = new JFrame("示例程序2");
        JPanel jp = new JPanel();
        JLabel j1 = new JLabel("请点击");
        JButton jb = new JButton("click");
        JButton jb1 = new JButton("click");
        ClickAction2 a = new ClickAction2();
        jb1.addActionListener(a);//如果jb1上发生了Action事件就执行a里面的代码
        jb.addActionListener(a);
        jp.add(j1);
        jp.add(jb);
        jp.add(jb1);
        j.add(jp);
        j.setSize(400, 200);
        j.setVisible(true);

    }

}

class ClickAction2 implements ActionListener{

    //事件发生时,actionPerformed方法会被虚拟机调用,事件对象回传给该方法
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
         long d = e.getWhen();//事件发生的事件
         Date date = new Date(d);//转化为相应的时间
         System.out.println(date);
         JButton sou = (JButton)e.getSource();//发生的事件源
         sou.setText("点不着");//将点击发生的按钮的按钮设为点不着
         //如果没有设置过ActionCommand,默认得到的是按钮的标题
         String com = e.getActionCommand();
         System.out.println("command is: " +com);
    }

}
Copy after login

3. Event type

There are many events in graphical interface development. These events With EventObject as the top level and class, a tree structure is formed according to the type of event.

See the figure below for details:

Detailed explanation of events in java with pictures and texts

EventObject is the parent class of all event classes, and it contains two methods:

(1), Object getSource(): The object where the Event originally occurred

(2), String toString(): Returns the String representation of this EventObject.

Through getSource(): You can know which object the event occurred on.

Regarding the meaning of other event classes, source code explanations and simple drills for several classes will be given below.

MouseEvent Class

When a component is pressed, released, clicked, moved or dragged, a mouse event is triggered.

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class MouseListenerTest {
    public static void main(String[] args) {
        JFrame j = new JFrame("我的窗口");
        MouL w = new MouL();
        j.addMouseListener(w);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class MouL implements MouseListener{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠标的位置: " + e.getX() + "," + e.getY());
        System.out.println("点击发生了");
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("按下");
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("松开");
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠标进入了窗口");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("鼠标离开了窗口");
    }
}
Copy after login

WindowEvent Class

Window events will be triggered when the window is opened, closed, maximized, or minimized

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class WindowsListenerTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("我的窗口");
        WindowL w = new WindowL();
        j.addWindowListener(w);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class WindowL implements WindowListener{

    @Override
    public void windowOpened(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口打开时我执行windowOpened");
    }

    @Override
    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("windowClosing");
    }

    @Override
    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口关闭时我执行windowClosed");
    }

    @Override
    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口最小化时我执行windowIconified");
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口回复时我执行windowDeiconified");
    }

    @Override
    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口变成活动状态时我执行mouseClicked");
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("窗口变成不活动状态时我执行windowDeactivated");
    }

}
Copy after login

ContainerEvent Class

When Events are triggered when a component is added to a container or when a component is removed from a container.

import java.awt.event.ContainerListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ContainerEvent {

    public static void main(String[] args) {

        JFrame j = new JFrame("我的窗口");
        ContL w = new ContL();
        JPanel jp = new JPanel();

        jp.addContainerListener(w);

        JButton del = new JButton("删除");
        JButton add = new JButton("add");

        jp.add(add);
        jp.add(del);//触发组件添加了

        jp.remove(del);//触发组件删除了

        j.getContentPane().add(jp);
        j.setSize(100, 100);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

}

class ContL implements ContainerListener{

    @Override
    public void componentAdded(java.awt.event.ContainerEvent e) {
        // TODO Auto-generated method stub
        System.out.println("组件添加了");
    }

    @Override
    public void componentRemoved(java.awt.event.ContainerEvent e) {
        // TODO Auto-generated method stub
        System.out.println("组件删除了");
    }

}
Copy after login

FocusEvent

Mouse clicks and other operations will cause a component to gain or lose focus. When a component gets focus, or loses focus, the focus event will be triggered

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FocusTest {

    public static void main(String[] args) {

        JFrame j = new JFrame("key test");
        JPanel jp = new JPanel();
        JButton j1 = new JButton("1");
        JButton j2 = new JButton("2");
        j1.addFocusListener(new FocusL());
        j2.addFocusListener(new FocusL());
        jp.add(j1);
        jp.add(j2);
        j.add(jp);
        j.setSize(600, 500);
        j.setVisible(true);
    }

}

class FocusL implements FocusListener{

    @Override
    public void focusGained(FocusEvent e) {
        //得到FocusEvent发生时的对象,转化为按钮
        // TODO Auto-generated method stub
        JButton j = (JButton)e.getSource();
        //得到按钮的标题
        String title = j.getText();
        System.out.println("focusGained:按钮" + title + "获得焦点");
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub
        JButton j = (JButton)e.getSource();
        String title = j.getText();
        System.out.println("focusLost:按钮" + title + "失去焦点");
    }

}
Copy after login

4. Multiple listeners

Generally, the event source can Many different types of events are generated, so many different types of listeners can be registered (triggered).

Multiple listeners can be registered on an event source component, and a listener can be registered on multiple different event sources.

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class MultiListenerTest {

    public static void main(String[] args) {

        JFrame a = new JFrame("事件处理");
        JTextField jf = new JTextField();
        a.add(jf, "South");
        MouseM m = new MouseM();

        //同一事件源上注册两个事件监听程序
        //鼠标的监听程序如点击等
        a.addMouseListener(m);

        //鼠标移动的监听程序
        a.addMouseMotionListener(m);

        a.setSize(200, 200);
        a.setVisible(true);
    }

}

class MouseM implements MouseMotionListener, MouseListener{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("clicked" + "x:" + e.getX() + ",y:" + e.getY());
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mousePressed");
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseRelsased");
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseEntered");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("mouseExited");
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("拖动:" + e.getPoint());
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("移动:" + e.getPoint());
    }

}
Copy after login

5. Event Adapter

To simplify programming, JDK defines corresponding implementation classes for most event listener interfaces - event adapter classes , in the adapter, implements all the methods in the corresponding listener interface, but does nothing.

So the defined listener class can inherit the event adapter class and only override the required methods.

There are the following adapters:

- ComponentAdapter (component adapter)

- ContainerAdapter (容器适配器)

- FocusAdapter (焦点适配器)

- KeyAdapter (键盘适配器)

- MouseAdapter (鼠标适配器)

- MouseMotionAdapter (鼠标运动适配器)

- WindowAdapter (窗口适配器)

鼠标适配器示例程序:MouseListener中由多个方法,但在这里只实现了mouseClicked()

package 图形界面设计;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;

public class AdapterTest {

    public static void main(String[] args) {

        JFrame z = new JFrame("事件适配器测试");
        z.setSize(500, 400);

        MouseLS a = new MouseLS();

        //注册z上的鼠标事件处理程序,发生点击等事件执行a里的代码
        z.addMouseListener(a);
        z.setVisible(true);
        z.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class MouseLS extends MouseAdapter{

    public void mouseClicked(MouseEvent e){

        // 打印出鼠标点击时的x点和y点的坐标
        System.out.println("鼠标点击了:" + e.getX() + "," + e.getY());
    }

}
Copy after login

更多java知识请关注java基础教程栏目。

The above is the detailed content of Detailed explanation of events in java with pictures and texts. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!