SWING - ActionListener 接口

处理 ActionEvent 的类应该实现这个接口。 该类的对象必须向组件注册。 可以使用 addActionListener() 方法注册对象。 当动作事件发生时,该对象的 actionPerformed 方法被调用。


接口声明

以下是 java.awt.event.ActionListener 接口的声明 −

public interface ActionListener
   extends EventListener

接口方法

序号 方法 & 描述
1

void actionPerformed(ActionEvent e)

在动作发生时调用。


继承的方法

这个接口继承了以下接口的方法 −

java.awt.EventListener


ActionListener 示例

D:/ > SWING > com > tutorialspoint > gui > 中使用您选择的任何编辑器创建以下 Java 程序

SwingListenerDemo.java

package com.tutorialspoint.gui;

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

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

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showActionListenerDemo();
   }
   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 showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            
      JButton okButton = new JButton("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);
      mainFrame.setVisible(true); 
   }
   class CustomActionListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }	
}

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

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

如果没有报错,说明编译成功。 使用以下命令运行程序。

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

验证以下输出。

SWING ActionListener

❮ SWING 事件监听器