📜  Java中的事件处理

📅  最后修改于: 2022-05-13 01:54:55.168000             🧑  作者: Mango

Java中的事件处理

一个事件 可以定义为通过执行动作来改变对象或行为的状态。动作可以是按钮点击、光标移动、通过键盘按键或页面滚动等。

Java.awt.event包可用于提供各种事件类。

事件分类

  • 前台事件
  • 背景事件

活动类型

1.前台事件

前台事件是需要用户交互产生的事件,即前台事件是由于用户在图形用户界面( GUI )中的组件上的交互而产生的。交互只不过是单击按钮、滚动滚动条、光标时刻等。

2. 背景事件

不需要用户交互来生成的事件称为后台事件。这些事件的示例是操作系统故障/中断、操作完成等。

事件处理

它是一种控制事件决定事件发生后应该发生什么的机制。为了处理这些事件, Java遵循委托事件模型。

委托事件模型

  • 它有来源和听众。

委托事件模型

  • 源:事件是从源生成的。有各种来源,如按钮、复选框、列表、菜单项、选择、滚动条、文本组件、窗口等,可以生成事件。
  • 侦听器:侦听器用于处理从源生成的事件。这些侦听器中的每一个都代表负责处理事件的接口。

要执行事件处理,我们需要向侦听器注册源。

向侦听器注册源

不同的类提供不同的注册方法。

句法:

addTypeListener()

其中 Type 表示事件的类型。

示例 1:对于KeyEvent ,我们使用addKeyListener()来注册。

例2:对于ActionEvent我们使用addActionListener()来注册。

Java中的事件类

Event Class

Listener Interface

Description

ActionEvent

ActionListener

An event that indicates that a component-defined action occurred like a button click or selecting an item from the menu-item list.

AdjustmentEvent

AdjustmentListener

The adjustment event is emitted by an Adjustable object like Scrollbar.

ComponentEvent

ComponentListener

An event that indicates that a component moved, the size changed or changed its visibility.

ContainerEvent

ContainerListener

When a component is added to a container (or) removed from it, then this event is generated by a container object.

FocusEvent

FocusListener

These are focus-related events, which include focus, focusin, focusout, and blur.

ItemEvent

ItemListener

An event that indicates whether an item was selected or not.

KeyEvent

KeyListener

An event that occurs due to a sequence of keypresses on the keyboard.

MouseEvent

MouseListener & MouseMotionListener

The events that occur due to the user interaction with the mouse (Pointing Device).

MouseWheelEvent

MouseWheelListener

An event that specifies that the mouse wheel was rotated in a component. 

TextEvent

TextListener

An event that occurs when an object’s text changes.

WindowEvent

WindowListener

An event which indicates whether a window has changed its status or not.

不同的接口由下面指定的不同方法组成。

Listener Interface

Methods

ActionListener

  • actionPerformed()

AdjustmentListener

  • adjustmentValueChanged()

ComponentListener

  • componentResized()
  • componentShown()
  • componentMoved()
  • componentHidden()

ContainerListener

  • componentAdded()
  • componentRemoved()

FocusListener

  • focusGained()
  • focusLost()

ItemListener

  • itemStateChanged()

KeyListener

  • keyTyped()
  • keyPressed()
  • keyReleased()

MouseListener

  • mousePressed()
  • mouseClicked()
  • mouseEntered()
  • mouseExited()
  • mouseReleased()

MouseMotionListener

  • mouseMoved()
  • mouseDragged()

MouseWheelListener

  • mouseWheelMoved()

TextListener

  • textChanged()

WindowListener

  • windowActivated()
  • windowDeactivated()
  • windowOpened()
  • windowClosed()
  • windowClosing()
  • windowIconified()
  • windowDeiconified()

事件处理流程

  1. 需要与组件进行用户交互才能生成事件。
  2. 相应事件类的对象是在事件生成后自动创建的,它保存了事件源的所有信息。
  3. 新创建的对象被传递给注册的监听器的方法。
  4. 该方法执行并返回结果。

代码方法

执行事件处理的三种方法是将事件处理代码放在下面指定的位置之一。

  1. 班内
  2. 其他类
  3. 匿名类

类内事件处理

Java
// Java program to demonstrate the
// event handling within the class
 
import java.awt.*;
import java.awt.event.*;
 
class GFG extends Frame implements ActionListener {
 
    TextField textField;
 
    GFGTop()
    {
        // Component Creation
        textField = new TextField();
 
        // setBounds method is used to provide
        // position and size of the component
        textField.setBounds(60, 50, 180, 25);
        Button button = new Button("click Here");
        button.setBounds(100, 120, 80, 30);
 
        // Registering component with listener
        // this refers to current instance
        button.addActionListener(this);
 
        // add Components
        add(textField);
        add(button);
 
        // set visibility
        setVisible(true);
    }
   
    // implementing method of actionListener
    public void actionPerformed(ActionEvent e)
    {
        // Setting text to field
        textField.setText("GFG!");
    }
   
    public static void main(String[] args)
    {
      new GFGTop();
    }
}


Java
// Java program to demonstrate the
// event handling by the other class
 
import java.awt.*;
import java.awt.event.*;
 
class GFG1 extends Frame {
   
    TextField textField;
   
    GFG2()
    {
        // Component Creation
        textField = new TextField();
       
        // setBounds method is used to provide
        // position and size of component
        textField.setBounds(60, 50, 180, 25);
        Button button = new Button("click Here");
        button.setBounds(100, 120, 80, 30);
       
        Other other = new Other(this);
       
        // Registering component with listener
        // Passing other class as reference
        button.addActionListener(other);
       
        // add Components
        add(textField);
        add(button);
       
        // set visibility
        setVisible(true);
    }
   
    public static void main(String[] args)
    {
      new GFG2();
    }
}


Java
/// import necessary packages
import java.awt.event.*;
 
// implements the listener interface
class Other implements ActionListener {
                          
    GFG2 gfgObj;
   
    Other(GFG1 gfgObj)
    {
      this.gfgObj = gfgObj;
    }
   
    public void actionPerformed(ActionEvent e)
    {
        // setting text from different class
        gfgObj.textField.setText("Using Different Classes");
    }
}


Java
// Java program to demonstrate the
// event handling by the anonymous class
 
import java.awt.*;
import java.awt.event.*;
 
class GFG3 extends Frame {
   
    TextField textField;
   
    GFG3()
    {
        // Component Creation
        textField = new TextField();
       
        // setBounds method is used to provide
        // position and size of component
        textField.setBounds(60, 50, 180, 25);
        Button button = new Button("click Here");
        button.setBounds(100, 120, 80, 30);
       
        // Registering component with listener anonymously
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                // Setting text to field
                textField.setText("Anonymous");
            }
        });
       
        // add Components
        add(textField);
        add(button);
       
        // set visibility
        setVisible(true);
    }
   
    public static void main(String[] args)
    {
        new GFG3();
    }
}



输出

单击后,文本字段值设置为 GFG!

解释

  1. 首先用小程序扩展类并实现相应的监听器。
  2. 创建文本字段和按钮组件。
  3. 使用相应的事件注册按钮组件。即addActionListener() 的ActionEvent。
  4. 最后,实现抽象方法。

其他类的事件处理

Java

// Java program to demonstrate the
// event handling by the other class
 
import java.awt.*;
import java.awt.event.*;
 
class GFG1 extends Frame {
   
    TextField textField;
   
    GFG2()
    {
        // Component Creation
        textField = new TextField();
       
        // setBounds method is used to provide
        // position and size of component
        textField.setBounds(60, 50, 180, 25);
        Button button = new Button("click Here");
        button.setBounds(100, 120, 80, 30);
       
        Other other = new Other(this);
       
        // Registering component with listener
        // Passing other class as reference
        button.addActionListener(other);
       
        // add Components
        add(textField);
        add(button);
       
        // set visibility
        setVisible(true);
    }
   
    public static void main(String[] args)
    {
      new GFG2();
    }
}

Java

/// import necessary packages
import java.awt.event.*;
 
// implements the listener interface
class Other implements ActionListener {
                          
    GFG2 gfgObj;
   
    Other(GFG1 gfgObj)
    {
      this.gfgObj = gfgObj;
    }
   
    public void actionPerformed(ActionEvent e)
    {
        // setting text from different class
        gfgObj.textField.setText("Using Different Classes");
    }
}


输出

处理来自不同类的事件

匿名类的事件处理

Java

// Java program to demonstrate the
// event handling by the anonymous class
 
import java.awt.*;
import java.awt.event.*;
 
class GFG3 extends Frame {
   
    TextField textField;
   
    GFG3()
    {
        // Component Creation
        textField = new TextField();
       
        // setBounds method is used to provide
        // position and size of component
        textField.setBounds(60, 50, 180, 25);
        Button button = new Button("click Here");
        button.setBounds(100, 120, 80, 30);
       
        // Registering component with listener anonymously
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                // Setting text to field
                textField.setText("Anonymous");
            }
        });
       
        // add Components
        add(textField);
        add(button);
       
        // set visibility
        setVisible(true);
    }
   
    public static void main(String[] args)
    {
        new GFG3();
    }
}


输出

匿名处理