[Java] ActionEvent 事件处理

来源:互联网 发布:淘宝宝贝修改主图 编辑:程序博客网 时间:2024/04/29 11:41

import java.awt.*;
import java.awt.event.*;
public class ActionEventTest{
    public static void main(String[] args){
        //创建frame and Button
        Frame f = new Frame("ActionEventTest");
        Button bStart = new Button("Start");
        Button bStop = new Button("Stop");
       
        //给button组件加班ActionListener,
        bStart.addActionListener(new ButtonActionEvent());
        //设置bStop按钮的ActionCommand为 "Game Over"
        bStop.setActionCommand("Game Over!");
        bStop.addActionListener(new ButtonActionEvent());
       
        //设置frame的布局并添加button
        f.setLayout(new BorderLayout());
        f.add(bStart,BorderLayout.NORTH);
        f.add(bStop,BorderLayout.SOUTH);
       
        //设置frame属性
        f.setLocationByPlatform(true);
        f.pack();
        f.setVisible(true);
        }
}
//创建 ActionListener 类,用接口的方法
class ButtonActionEvent implements ActionListener{
    //重写 actionPerformed()方法
    public void actionPerformed(ActionEvent e){
        //输出ActionCommand的内容
        System.out.println(e.getActionCommand());
    }
}

//actionCommand属性用于记录按钮/菜单类组件所激发的ActionEvent事件相关指令信息

原创粉丝点击