修飾子
public interface ActionListener
父介面
java.util.EventListener
實作方法
名稱 敘述 actionPerformed() 設定按下按鈕後的動作
舉例如下
import java.awt.*;
import java.awt.event.*;
public class ActionEventDemo implements ActionListener {
public static void main(String[] args) {
new ActionEventDemo();
}
public ActionEventDemo() {
Frame frame = new Frame("AWTDemo");
frame.addWindowListener(new AdapterDemo());
frame.setLayout(new FlowLayout());
Button button = new Button("demo");
button.setActionCommand("d1");
button.addActionListener(this);
frame.add(button);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd == "d1") {
System.out.println("Yes....");
}
}
}
class AdapterDemo extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:ActionEventDemo.java
功能:示範 Java 程式
作者:張凱慶
時間:西元 2012 年 3 月 */此例的 ActionEventDemo 有實作 ActionListener 介面
public class ActionEventDemo implements ActionListener {因此需要實作 actionPerformed() 方法,參數 e 就是 ActionEvent 物件,接著呼叫 ActionEvent 的 getActionCommand() 取得按鈕設定的指令,若指令相符就在命令列印出 "Yes...."
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd == "d1") {
System.out.println("Yes....");
}
}編譯後執行,結果如下

| 中英文術語對照 | |
|---|---|
| 介面 | interface |
| 方法 | method |
| 參數 | parameter |
| 物件 | object |
您可以繼續參考
事件處理
相關目錄
Java API 分類導覽
Java 教材
首頁
參考資料
http://docs.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html
沒有留言:
張貼留言