Swing 简明教程

SWING - Event Handling

在本章中,你将了解事件、其类型,以及如何处理事件。本文末尾提供了示例,以帮助你更好地理解。

In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.

What is an Event?

对象的上述状态变化称为 Event ,即事件描述了源状态的变化。事件是用户与图形用户界面组件交互的结果而生成的。例如,单击按钮、移动鼠标、通过键盘输入字符、从列表中选择项目以及滚动页面都是导致事件发生的活动。

Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.

Types of Event

事件可以大致分为两类 −

The events can be broadly classified into two categories −

  1. Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.

  2. Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.

What is Event Handling?

事件处理是控制事件并决定如果发生事件应发生什么的机制。此机制具有一个代码,称为事件处理程序,该代码在事件发生时执行。

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.

Java 使用委派事件模型来处理事件。此模型定义了生成和处理事件的标准机制。

Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.

委托事件模型具有以下关键参与者。

The Delegation Event Model has the following key participants.

  1. Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide us with classes for the source object.

  2. Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.

此方法的优点是,用户界面逻辑与生成事件的逻辑完全分离。用户界面元素能够将事件处理委托给单独的一段代码。

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.

在此模型中,侦听器需要向源对象注册,以便侦听器可以接收事件通知。这是一​​种处理事件的有效方法,因为只有希望接收事件的侦听器才会收到事件通知。

In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them.

Steps Involved in Event Handling

Step 1 −用户单击按钮,生成事件。

Step 1 − The user clicks the button and the event is generated.

Step 2 −自动创建有关事件类的对象,并将有关源和事件的信息填充到同一对象中。

Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.

Step 3 −事件对象转到已注册侦听器类的,方法。

Step 3 − Event object is forwarded to the method of the registered listener class.

Step 4 −该方法得到执行并返回。

Step 4 − The method is gets executed and returns.

Points to Remember About the Listener

  1. In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.

  2. If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object.

Callback Methods

这些方法由 API 供应商提供并且由应用程序程序员定义,由应用程序开发人员调用。此处,回调方法表示事件方法。响应事件,java jre 将激发回调方法。所有此类回调方法都包含在侦听器接口中。

These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces.

如果某个组件希望有侦听器来侦听其事件,则源必须向侦听器注册自身。

If a component wants some listener to listen ot its events, the source must register itself to the listener.

Event Handling Example

使用您选择的任意编辑器,使用以下命令创建 Java 程序,例如 D:/ > SWING > com > tutorialspoint > gui >

Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >

SwingControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingControlDemo swingControlDemo = new SwingControlDemo();
      swingControlDemo.showEventDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);
      statusLabel.setSize(350,100);

      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);
   }
   private void showEventDemo(){
      headerLabel.setText("Control in action: Button");

      JButton okButton = new JButton("OK");
      JButton submitButton = new JButton("Submit");
      JButton cancelButton = new JButton("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener());
      submitButton.addActionListener(new ButtonClickListener());
      cancelButton.addActionListener(new ButtonClickListener());

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);

      mainFrame.setVisible(true);
   }
   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();

         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         } else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked.");
         } else {
            statusLabel.setText("Cancel Button clicked.");
         }
      }
   }
}

使用命令提示符编译程序。转到 D:/ > SWING 然后键入以下命令。

Compile the program using the command prompt. Go to D:/ > SWING and type the following command.

D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java

如果没有发生任何错误,则表示编译成功。使用以下命令运行程序。

If no error occurs, it means the compilation is successful. Run the program using the following command.

D:\AWT>java com.tutorialspoint.gui.SwingControlDemo

验证以下输出。

Verify the following output.

swing button