给按钮注册事件监听器

来源:互联网 发布:黑河教务网络管理系统 编辑:程序博客网 时间:2024/05/04 00:53


import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**
 * 给按钮注册事件监听器
 * @author Chenkunqing
 *
 */
public class TestButtonListener {
public static void main(String[] args) {
new MyButton();
}
}
class MyButton extends Frame{
public MyButton(){
this.setBounds(300,300,400,400);
this.setVisible(true);

// 窗口显示界面设置。
Button b = new Button("Login");
b.addActionListener(new MyActionListener());
Panel panel = new Panel();
panel.add(b);
this.add(panel);
}

}
class MyActionListener implements ActionListener{
// 事件处理方法
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("有人点击了按钮");
System.out.println(((Button)e.getSource()).getLabel());
// e.getSource()获得事件源,即获得你操作了哪个控件,getLabel()是获得标签名。
}



}

原创粉丝点击