509.md 2.6 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8
# 如何编写可撤销的编辑监听器

> 原文: [https://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html](https://docs.oracle.com/javase/tutorial/uiswing/events/undoableeditlistener.html)

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

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

W
wizardforcel 已提交
9
```java
W
init  
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
...
//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();
    }
}  

```

W
wizardforcel 已提交
25
您可以在[示例索引中找到使用 Swing 组件](../examples/components/index.html#TextComponentDemo)`TextComponentDemo`源文件的链接。有关程序的可撤消编辑监听器方面的讨论,请参阅[实现撤消和重做](../components/generaltext.html#undo)
W
init  
wizardforcel 已提交
26

W
wizardforcel 已提交
27
*因为`UndoableEditListener`只有一个方法,所以它没有相应的适配器类。*
W
init  
wizardforcel 已提交
28 29 30 31 32 33 34 35

| 方法 | 目的 |
| :-- | :-- |
| [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--)
W
wizardforcel 已提交
36
`java.util.EventObject`中的*)_ | 返回触发事件的对象。 |
W
init  
wizardforcel 已提交
37 38
| [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) 对象,该对象表示发生的编辑,包含有关撤消或重做编辑的信息和命令。 |

W
wizardforcel 已提交
39
下表列出了使用可撤消编辑监听器的示例。
W
init  
wizardforcel 已提交
40 41 42

| 例 | 在哪里描述 | 笔记 |
| :-- | :-- | :-- |
W
wizardforcel 已提交
43
| [`TextComponentDemo`](../examples/components/index.html#TextComponentDemo) | [实现撤销和重做](../components/generaltext.html#undo) | 在可撤消编辑监听器的帮助下,在文本窗格上实现撤消和重做。 |