ActionListener的用法

来源:互联网 发布:北京云狐网络 编辑:程序博客网 时间:2024/06/10 07:53
ActionListener是Java中关于事件处理的一个接口,继承自EventListener。
ActionListener用于接收操作事件的侦听器接口。对处理操作事件感兴趣的类可以实现此接口,而使用该类创建的对象可使用组件的 addActionListener 方法向该组件注册。在发生操作事件时,调用该对象的 actionPerformed 方法。
以下为示例代码:(简单的代码供大家学习和参考)
package org.gan.listener;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
public class ActionListener {
Frame f = new Frame();
Panel p = new Panel();
TextField txtField = new TextField(50);
Button btn = new Button("提交");
public void init() {
f.setLayout(new FlowLayout());
// 注册ActionListener接口
p.add(txtField);
p.add(btn);
btn.addActionListener(new myActionListener());
f.setBackground(Color.GRAY);
f.add(p);
// 设置标题
f.setTitle("事件处理程序");
// 设置尺寸,默认为(0,0)
f.setSize(500, 500);
// 设置是否可见,默认为false
f.setVisible(true);
}
// 实现ActionListener接口 public class myActionListen implements java.awt.event.ActionListener {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
txtField.setText("Hello World!");
}
}
public static void main(String[] agrs) {
new ActionListener().init();
}
}

0 0