- SWING 教程
- SWING - 首页
- SWING - 概览
- SWING - 环境
- SWING - 控件
- SWING - 事件处理
- SWING - 事件类
- SWING - 事件侦听器
- SWING - 事件适配器
- SWING - 布局
- SWING - 菜单
- SWING - 容器
- SWING 实用资源
- SWING - 快速指南
- SWING - 实用资源
- SWING - 讨论
SWING - ActionListener 接口
处理ActionEvent的类应实现此接口。该类的对象必须向组件注册。可以通过addActionListener()方法来注册对象。在发生操作事件时,将调用该对象的actionPerformed方法。
界面声明
以下是java.awt.event.ActionListener接口的声明 -
public interface ActionListener extends EventListener
界面方法
| 编号 | 方法和说明 |
|---|---|
| 1 |
void actionPerformed(ActionEvent e) 在发生操作时调用。 |
继承方法
此界面继承以下界面的方法 -
java.awt.EventListener
ActionListener 示例
在您选择的任何编辑器中,在D:/ > SWING > com > tutorialspoint > gui >中创建如下的 Java 程序
SwingListenerDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingListenerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingListenerDemo swingListenerDemo = new SwingListenerDemo();
swingListenerDemo.showActionListenerDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
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.magenta);
JButton okButton = new JButton("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:/ > SWING,输入以下命令。
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java
如果未出现错误,则表示编译成功。使用以下命令运行程序。
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo
验证以下输出。
swing_event_listeners.htm
广告