Java Reference
In-Depth Information
public void actionPerformed(ActionEvent actionEvent) {
try {
undoManager.redo();
} catch (CannotRedoException cannotRedoException) {
showMessage(actionEvent.getSource());
}
}
}
}
■
Note
One thing you can do to improve these helper actions is to have them enabled only when the particular
operation is available. The
AbstractUndoableEdit.redoText
and
AbstractUndoableEdit.undoText
usages are listed in Table 21-1.
The rest of the source for the example shown in Figure 21-1 is provided in Listing 21-2.
With the help of the new
UndoManagerHelper
class, the most difficult part of using the Undo
Framework with the Swing text components has been greatly simplified.
Listing 21-2.
UndoManager Example with Swing Text Components
import javax.swing.*;
import javax.swing.undo.*;
import java.awt.*;
public class UndoSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Undo Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
UndoManager manager = new UndoManager();
textArea.getDocument().addUndoableEditListener(manager);
JToolBar toolbar = new JToolBar();
JButton undoButton =
new JButton(UndoManagerHelper.getUndoAction(manager));
toolbar.add(undoButton);
JButton redoButton =
new JButton(UndoManagerHelper.getRedoAction(manager));
toolbar.add(redoButton);