Chapter 18. Undo

In many applications (word processors, spreadsheets, board games, etc.) the user is given the opportunity to undo changes made to the state of the application. In a word processor you can (thankfully!) 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 uses 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. That discussion will be ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.