處理ActionEvent
的類應該實現此介面。該類的物件必須在元件中註冊。可以使用addActionListener()
方法註冊該物件。當動作事件發生時,將呼叫該物件的actionPerformed
方法。
以下是java.awt.event.ActionListener
介面的宣告 -
public interface ActionListener
extends EventListener
編號 | 方法 | 描述 |
---|---|---|
1 | void actionPerformed(ActionEvent e) |
發生操作時呼叫。 |
此介面從以下介面繼承方法 -
java.awt.EventListener
使用編輯器建立以下Java程式:ActionListenerExample.java
package com.yiibai.swing.listener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionListenerExample {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public ActionListenerExample() {
prepareGUI();
}
public static void main(String[] args) {
ActionListenerExample swingListenerDemo = new ActionListenerExample();
swingListenerDemo.showActionListenerDemo();
}
private void prepareGUI() {
// from https://www.tw511.com/swing/
mainFrame = new JFrame("Java SWING ActionListener範例");
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.ORANGE);
JButton okButton = new JButton("確定");
okButton.addActionListener(new CustomActionListener());
panel.add(okButton);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("點選了'確定'按鈕");
}
}
}
執行上面範例程式碼,得到以下結果: