学习监听事件
单监听事件
当我们点击按钮时,控制台能得到执行这个按钮产生的行为,即点击这个按钮得到什么样的结果,这就是事件的监听
实现代码:
//行为事件
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame = new Frame();
Button button = new Button("test");
//因为addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
//把button放到frame的中间
frame.add(button,BorderLayout.CENTER);
//自适应大小
frame.pack();
frame.setVisible(true);
//关闭窗口事件
windowClose(frame);
}
//关闭窗体的事件方法
private 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");
}
}
=============================================================================================
两个按钮实现同一个监听
对于 button1代码里面没有显示定义,所以在点击button1之后,控制台就默认显示:start
但是对于button2按钮,我是在里面有显示定义的所以显示的信息为:button2-stop
实现代码:
//开始 停止
public class TestActionTwo {
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);
windowClose(frame);
}
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyMonitor implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了:msg-->"+e.getActionCommand());
if (e.getActionCommand().equals("stop")){
}
}
}
补充说明:最后的if里面是一个判断语句,当按钮满足某些情况时就可以将满足实现的代码写到里面,当不满足情况时就执行另外的一条语句,这样就避免了重复写代码,实现
多个按钮只写一个监听类,减少代码量。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律