如何编写可撤销的编辑监听器

原文: https://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html

当组件上可以撤消的操作发生时,会发生可撤消的编辑事件。目前,只有文本组件触发可撤消的编辑事件,然后才会间接触发。文本组件的文档触发事件。对于文本组件,可撤消操作包括插入字符,删除字符和修改文本样式。程序通常会侦听可撤消的编辑事件,以帮助执行撤消和重做命令。

以下是来自名为TextComponentDemo的应用程序的可撤消编辑事件处理代码。

  1. ...
  2. //where initialization occurs
  3. document.addUndoableEditListener(new MyUndoableEditListener());
  4. ...
  5. protected class MyUndoableEditListener implements UndoableEditListener {
  6. public void undoableEditHappened(UndoableEditEvent e) {
  7. //Remember the edit and update the menus
  8. undo.addEdit(e.getEdit());
  9. undoAction.updateUndoState();
  10. redoAction.updateRedoState();
  11. }
  12. }

您可以在示例索引中找到使用 Swing 组件TextComponentDemo源文件的链接。有关程序的可撤消编辑监听器方面的讨论,请参阅实现撤消和重做

因为UndoableEditListener只有一个方法,所以它没有相应的适配器类。

方法 目的
undoableEditHappened(UndoableEditEvent) 在侦听组件上发生可撤消事件时调用。
方法 目的
对象 getSource()

java.util.EventObject中的*)_ | 返回触发事件的对象。 | | UndoableEdit getEdit() | 返回 UndoableEdit 对象,该对象表示发生的编辑,包含有关撤消或重做编辑的信息和命令。 |

下表列出了使用可撤消编辑监听器的示例。

在哪里描述 笔记
TextComponentDemo 实现撤销和重做 在可撤消编辑监听器的帮助下,在文本窗格上实现撤消和重做。