标签:
一、事件监听
package com.lost.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class Monitor2 implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("a button has been pressed,"+"the relative info is:\n"+e.getActionCommand());
/*使用返回的监听对象e调用getActionCommand()方法获取两个按钮执行单击命令后的返回信息
根据返回信息的不同区分开当前操作的是哪一个按钮,btn1没有使用setActionCommand()方法设置
则btn1返回的信息就是按钮上显示的文本*/
}
}
public class ActionEventDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame f = new Frame("ActionEventDemo2");
Button btn1 = new Button("start");
Button btn2 = new Button("stop");
Monitor2 m2 = new Monitor2();
btn1.addActionListener(m2);
btn1.setActionCommand("Game Start()");
btn2.addActionListener(m2);
f.add(btn1,BorderLayout.NORTH);
f.add(btn2,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
addWindowClosingEvent(f);
}
private static void addWindowClosingEvent(Frame f)
{
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
super.windowClosing(e);
System.exit(0);
}
});
}
}
为Componet添加监听对象,设置监听动作。
二、TextField事件监听
TextField对象可能发生Action(光标在文本框内敲回车)事件,与该事件对应的事件类是java.awt.event.ActionEvent。
用来处理ActionEvent事件是实现了java.awt.event.ActionListener接口的类对象。ActionListener接口定义有方法:
public void actionPerformed(ActionEvent e)
实现该接口的类要在该方法中添加处理事件(Action)语句
使用addActionListener(ActonListener l)方法为TextField对象注册一个ActionListener对象,当TextField对象发生Action事件时,会生成一个ActionEvent对象,该对象作为参数传递给ActionListener对象的actionPerformer方法在方法中可以获取该对象的信息,并作相应的处理。
标签:
原文地址:http://www.cnblogs.com/lobsterIT/p/4800627.html