Java Reference
In-Depth Information
public void redo() method. The undo() method and redo() method each throws a different
exception that must be dealt with.
Because the functionality necessary for the Undo and Redo buttons is the same for all
managers, you'll find a helper UndoManagerHelper class included in Listing 21-1 to create Action
objects for you. These objects can be used by a JMenuBar , JToolBar , or anything else that can
respond with an ActionListener for dealing with the undo and redo operations. You need to
ask the helper class for each Action , and then associate that Action with the appropriate
component. For instance, the following five lines of source code will take a previously created
UndoManager and add the necessary buttons for a JToolBar :
JToolBar toolbar = new JToolBar();
JButton undoButton = new JButton(UndoManagerHelper.getUndoAction(manager));
toolbar.add(undoButton);
JButton redoButton = new JButton(UndoManagerHelper.getRedoAction(manager));
toolbar.add(redoButton);
Using the undo facility with the Swing text components is that easy. The UndoManagerHelper
class definition is shown in Listing 21-1. If you don't like the default button labels (shown in
Figure 21-1), additional methods are available that support customization. In addition, if an
exception is thrown during the undo/redo operation, a warning message pops up. The warning
message and pop-up window title are also customizable.
Listing 21-1. The UndoManagerHelper Class Definition
import javax.swing.*;
import javax.swing.undo.*;
import java.awt.*;
import java.awt.event.*;
public class UndoManagerHelper {
public static Action getUndoAction(UndoManager manager, String label) {
return new UndoAction(manager, label);
}
public static Action getUndoAction(UndoManager manager) {
return new UndoAction(manager,
(String)UIManager.get("AbstractUndoableEdit.undoText"));
}
public static Action getRedoAction(UndoManager manager, String label) {
return new RedoAction(manager, label);
}
public static Action getRedoAction(UndoManager manager) {
return new RedoAction(manager,
(String)UIManager.get("AbstractUndoableEdit.redoText"))
}
Search WWH ::




Custom Search