站内搜索: 请输入搜索关键词
当前页面: 图书首页 > JFC Swing Tutorial, The: A Guide to Constructing GUIs, Second Edition

How to Write an Undoable Edit Listener - JFC Swing Tutorial, The: A Guide to Constructing GUIs, Second Edition

Previous Section  < Day Day Up >  Next Section

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's the undoable edit event handling code from an application called TextComponentDemo.[36]

[36] The source code, TextComponentDemo.java, is on the CD at: JavaTutorial/uiswing/components/example-1dot4/TextComponentDemo.java.


...

//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();

    }

}

For a discussion about the undoable edit listener aspect of the program see Implementing Undo and Redo (page 68) in Chapter 3.

The Undoable Edit Listener API

Table 42 lists the only method in the UndoableEditListener interface and Table 43 describes the methods in the UndoableEditEvent class. Note that UndoableEditListener has no corresponding adapter class. Also refer to the UndoableEditListener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/UndoableEditListener.html. The UndoableEditEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/UndoableEditEvent.html.

Table 42. The UndoableEditListener Interface

Method

Purpose

undoableEditHappened(UndoableEditEvent)

Called when an undoable event occurs on the listened-to component.

Table 43. The UndoableEditEvent Class

Method

Purpose


Object getSource()

(in java.util.EventObject)

Return the object that fired the event.

UndoableEdit getEdit()

Return an UndoableEdit 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 example that uses undoable edit listeners.

Example

Where Described

Notes

TextComponentDemo

Implementing Undo and Redo (page 68)

Implements undo and redo on a text pane with help from an undoable edit listener.

    Previous Section  < Day Day Up >  Next Section