The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners

How to Write an Undoable Edit Listener

Undoable edit events occur when an operation that can be undone occurs on a component. Currently, only text components fire undoable edit events, and then only indirectly. The text component's document fires the events. For text components, undoable operations include inserting characters, deleting characters, and modifying the style of text. Programs typically listen to undoable edit events to assist in the implementation of undo and redo commands.

Here is the undoable edit event handling code from an application called 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();
    }
}  
You can find the full source code for the program and instructions for compiling and running it in General Rules for Using Text Components(in the Creating a User Interface trail). For a discussion about the undoable edit listener aspect of the program see Implementing Undo and Redo(in the Creating a User Interface trail)

The Undoable Edit Event API

The UndoableEditListener interface has just one method, so it has no corresponding adapter class. Here's the method:
void undoableEditHappened(UndoableEditEvent)
Called when an undoable event occurs on the listened-to component.
The undoableEditHappened method has a single parameter: a UndoableEditEvent(in the API reference documentation) object. To get the document that fired the event, use the getSource method which UndoableEditEvent inherits from EventObject.

The UndoableEditEvent class defines one method which returns an object that contains detailed information about the edit that occurred.

UndoableEdit getEdit()
Returns an UndoableEdit(in the API reference documentation) object that represents the edit that occurred and contains information about and commands for undoing or redoing the edit.

Examples that Use Undoable Edit Listeners

The following table lists the examples that use undoable edit listeners.

Example Where Described Notes
TextComponentDemo Implementing Undo and Redo(in the Creating a User Interface trail) Implements undo and redo on a text pane with help from an undoable edit listener.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search