# 如何编写可撤销的编辑监听器 > 原文: [https://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html](https://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html) 当组件上可以撤消的操作发生时,会发生可撤消的编辑事件。目前,只有文本组件触发可撤消的编辑事件,然后才会间接触发。文本组件的文档触发事件。对于文本组件,可撤消操作包括插入字符,删除字符和修改文本样式。程序通常会侦听可撤消的编辑事件,以帮助执行撤消和重做命令。 以下是来自名为`TextComponentDemo`的应用程序的可撤消编辑事件处理代码。 ``` ... //where initialization occurs document.addUndoableEditListener(new MyUndoableEditListener()); ... protected class MyUndoableEditListener implements UndoableEditListener { public void undoableEditHappened(UndoableEditEvent e) { //Remember the edit and update the menus undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } ``` 您可以在[示例索引中找到使用 Swing 组件](../examples/components/index.html#TextComponentDemo)的`TextComponentDemo`源文件的链接。有关程序的可撤消编辑监听器方面的讨论,请参阅[实现撤消和重做](../components/generaltext.html#undo) _ 因为`UndoableEditListener`只有一个方法,所以它没有相应的适配器类。_ | 方法 | 目的 | | :-- | :-- | | [undoableEditHappened(UndoableEditEvent)](https://docs.oracle.com/javase/8/docs/api/javax/swing/event/UndoableEditListener.html#undoableEditHappened-javax.swing.event.UndoableEditEvent-) | 在侦听组件上发生可撤消事件时调用。 | | 方法 | 目的 | | :-- | :-- | | [对象 getSource()](https://docs.oracle.com/javase/8/docs/api/java/util/EventObject.html#getSource--) (`java.util.EventObject` 中的 _)_ | 返回触发事件的对象。 | | [UndoableEdit getEdit()](https://docs.oracle.com/javase/8/docs/api/javax/swing/event/UndoableEditEvent.html#getEdit--) | 返回 [`UndoableEdit`](https://docs.oracle.com/javase/8/docs/api/javax/swing/undo/UndoableEdit.html) 对象,该对象表示发生的编辑,包含有关撤消或重做编辑的信息和命令。 | 下表列出了使用可撤消编辑监听器的示例。 | 例 | 在哪里描述 | 笔记 | | :-- | :-- | :-- | | [`TextComponentDemo`](../examples/components/index.html#TextComponentDemo) | [实现撤销和重做](../components/generaltext.html#undo) | 在可撤消编辑监听器的帮助下,在文本窗格上实现撤消和重做。 |