目录

ActionListener

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

接口声明 (Interface Declaration)

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

public interface ActionListener
   extends EventListener

接口方法

Sr.No. 方法和描述
1

void actionPerformed(ActionEvent e)

发生操作时调用。

方法继承 (Methods Inherited)

此接口从以下接口继承方法 -

java.awt.EventListener

ActionListener示例

使用您选择的任何编辑器创建以下Java程序,例如D:/ 》 SWING 》 com 》 iowiki 》 gui 》

SwingListenerDemo.java

package com.iowiki.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\iowiki\gui\SwingListenerDemo.java

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

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

验证以下输出。

SWING ActionListener
↑回到顶部↑
WIKI教程 @2018