您的位置:首页 > 教育 > 锐评 > GUI编程05:事件监听

GUI编程05:事件监听

2025/6/10 0:00:28 来源:https://blog.csdn.net/zhangjinajian759/article/details/141872105  浏览:    关键词:GUI编程05:事件监听

本节内容视频链接:13、键盘监听事件_哔哩哔哩_bilibiliicon-default.png?t=N7T8https://www.bilibili.com/video/BV1DJ411B75F?p=13&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5

事件监听:当某个事情发生时,做什么,一般会和按钮配合使用。

代码示例:

public class TestActionEvent {public static void main(String[] args) {//按下按钮的时候触发一些事件Frame frame = new Frame("按钮");Button button = new Button("请点我");//因为addActionListener()需要一个ActionListener,所以我们需要构建一个ActionListenerMyActionListener 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() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});}
}//事件监听,用实现接口类的方式
class MyActionListener implements ActionListener{@Overridepublic 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{@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("按钮被点击了" + e.getActionCommand());}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com