处理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.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 http://www.yiibai.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("点击了'确定'按钮");
}
}
}
执行上面示例代码,得到以下结果: