AWT ActionListener 介面



應該實現此介面以處理 ActionEvent 的類。必須向元件註冊該類的物件。可以利用 addActionListener() 方法註冊該物件。當 Action 事件發生時,會呼叫該物件的 actionPerformed 方法。

介面宣告

以下是對 java.awt.event.ActionListener 介面的宣告

public interface ActionListener
   extends EventListener

介面方法

序號方法和說明
1

void actionPerformed(ActionEvent e)

在操作發生時呼叫。

繼承方法

此介面從以下介面繼承方法

  • java.awt.EventListener

ActionListener 示例

使用任意編輯器(比如 D:/ > AWT > com > tutorialspoint > gui > 中的編輯器)建立以下 Java 程式。

AwtListenerDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showActionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      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");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Button okButton = new Button("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:/ > AWT 並輸入以下命令。

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

如果沒有錯誤提示,這意味著編譯成功。使用以下命令執行此程式。

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

驗證以下輸出

AWT ActionListener
awt_event_listeners.htm
廣告