Event Listener's Adapter Classes
摘自: http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html Refer to the WindowEventDemo, a WindowEvent listener is required to implement the WindowListener interface,
which declares 7 abstract methods. Although we are only interested in windowClosing(), we need to provide
an empty body to the other 6 methods in order to compile the program. This is tedious. 当实现例如WindowListener接口的时候,虽然只需要用到其中的一个函数,但是却需要将其他的函数都写出,这样非常多余。 An adapter class called WindowAdapter is therefore provided, which implements the WindowListener interface
and provides default implementations to all the 7 abstract methods. You can then derive a subclass from
WindowAdapter and override only methods of interest and leave the rest to their default implementation. 有了adapter类之后,就只需要写出需要实现的方法就行,其他不需要使用的函数就不用写出。
import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class WindowEventDemoAdapter extends Frame { private TextField tfCount; private int count = 0; /** Constructor to setup the GUI */ public WindowEventDemoAdapter () { setLayout(new FlowLayout()); add(new Label("Counter")); tfCount = new TextField("0", 10); tfCount.setEditable(false); add(tfCount); Button btnCount = new Button("Count"); add(btnCount); btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + ""); } }); // Allocate an anonymous instance of an anonymous inner class // that extends WindowAdapter. // "this" Frame adds the instance as WindowEvent listener. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); // Terminate the program } }); setTitle("WindowEvent Demo"); setSize(250, 100); setVisible(true); } /** The entry main method */ public static void main(String[] args) { new WindowEventDemoAdapter(); // Let the constructor do the job } } Similarly, adapter classes such as MouseAdapter, MouseMotionAdapter, KeyAdapter, FocusAdapter are available for
MouseListener, MouseMotionListener, KeyListener, and FocusListener, respectively. There is no ActionAdapter for ActionListener, because there is only one abstract method (i.e. actionPerformed())
declared in the ActionListener interface. This method has to be overridden and there is no need for an adapter.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?