事件监听:当某个事情发生时,做什么,一般会和按钮配合使用。
代码示例:
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮的时候触发一些事件
Frame frame = new Frame("按钮");
Button button = new Button("请点我");
//因为addActionListener()需要一个ActionListener,所以我们需要构建一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button);
frame.setVisible(true);
frame.pack();
windowClose(frame);//关闭窗口
}
//关闭窗口方法
public static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件监听,用实现接口类的方式
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
代码示例2:两个或者多个按钮公用一个监听类,然后根据按钮上的不同信息判断需要执行什么命令。
public class TestActionEvent02 {
public static void main(String[] args) {
//两个按钮,实现同一个监听;
//开始按钮 停止按钮
Frame frame = new Frame("我的窗口");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//显示的定义出发会返回的命令,如果不显示定义,则会输出按钮上默认的值
button2.setActionCommand("button2-stop");
MyMonitor myMonitor = new MyMonitor();
button1.addActionListener(myMonitor);
button2.addActionListener(myMonitor);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了" + e.getActionCommand());
}
}

被折叠的 条评论
为什么被折叠?



