Chapter 18. Undo

In many applications (word processors, spreadsheets, and board games, to name a few), the user is given the opportunity to undo changes made to the state of the application. In a word processor you can undo deletions. In a chess game, you’re often allowed to take back undesirable moves (typically after realizing your queen has just been banished from the board). Without support, providing these undo capabilities can be a lot of work for the programmer, especially if you want to provide a powerful undo system that keeps a history of undoable operations and allows them to be undone and redone indefinitely.

Thankfully, Swing provides a collection of classes and interfaces that support this advanced undo functionality. Within the Swing packages, only the classes in the javax.swing.text package currently use these facilities, but you are free to use undo in any component you create or extend. You can even use it for undoing things that may not be directly associated with a UI component (like a chess move). It’s important to realize that the undo facility is not tied in any way to the Swing components themselves. One could easily argue that the package might be more logically called "java.util.undo.” None of the classes or interfaces in the javax.swing.undo package use any other Swing object.

In this chapter, we’ll look at everything Swing provides to support undo, but we won’t get into the details of how the text components use this facility (Chapter 22 does the honors ...

Get Java Swing, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.