16

I've created an XML editor and I'm stuck at the last phase: adding undo/redo functionality.

I've only got to add undo/redo for when users add elements, attributes, or text to the JTree.

I'm still quite new at this but in school today I attempted (unsuccessfully) to create two stack object []'s called undo and redo and to add the actions performed into them.

For instance, I have:

Action AddElement() {

// some code
public void actionPerformed(ActionEvent e) {

                    performElementAction();
                }
}

the performElementAction just actually adds an Element to the JTree.

I want to add a way to add this action performed to my undo stack. is there a simple way to just undo.push( the entire action performed) or something?

qwerty
  • 810
  • 1
  • 9
  • 26
Chea Indian
  • 677
  • 3
  • 9
  • 16
  • 1
    Be sure to take a look at the built-in undo support; I've never used it and I can't find a Swing tutorial for it, but [here](http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/UndoManager.html) is the manager. – Nate W. Jul 17 '12 at 20:30
  • Take a look at the [Command Pattern](https://en.wikipedia.org/wiki/Command_pattern), its uses include implementing undo/redo functionality. – Óscar López Jul 17 '12 at 20:24

3 Answers3

19

TL;DR: You can support undo and redo actions by implementing the Command (p.233) and Memento (p.283) patterns (Design Patterns - Gamma et. al).

The Memento Pattern

This simple pattern allows you to save the states of an object. Simply wrap the object in a new class and whenever its state changes, update it.

public class Memento
{
    MyObject myObject;
    
    public MyObject getState()
    {
        return myObject;
    }
    
    public void setState(MyObject myObject)
    {
        this.myObject = myObject;
    }
}

The Command Pattern

The Command pattern stores the original object (that we want to support undo/redo) and the memento object, which we need in case of an undo. Moreover, 2 methods are defined:

  1. execute: executes the command
  2. unExecute: removes the command

Code:

public abstract class Command
{
    MyObject myObject;
    Memento memento;
    
    public abstract void execute();
    
    public abstract void unExecute();
}

They define the logical "Actions" that extend Command (e.g. Insert):

public class InsertCharacterCommand extends Command
{
    //members..

    public InsertCharacterCommand()
    {
        //instantiate 
    }

    @Override public void execute()
    {
        //create Memento before executing
        //set new state
    }

    @Override public void unExecute()
    {
        this.myObject = memento.getState()l
    }
}

Applying the patterns:

This last step defines the undo/redo behavior. The core idea is to store a stack of commands that works as a history list of the commands. To support redo, you can keep a secondary pointer whenever an undo command is applied. Note that whenever a new object is inserted, then all the commands after its current position get removed; that's achieved by the deleteElementsAfterPointer method defined below:

private int undoRedoPointer = -1;
private Stack<Command> commandStack = new Stack<>();

private void insertCommand()
{
    deleteElementsAfterPointer(undoRedoPointer);
    Command command =
            new InsertCharacterCommand();
    command.execute();
    commandStack.push(command);
    undoRedoPointer++;
}

private void deleteElementsAfterPointer(int undoRedoPointer)
{
    if(commandStack.size()<1)return;
    for(int i = commandStack.size()-1; i > undoRedoPointer; i--)
    {
        commandStack.remove(i);
    }
}

  private void undo()
{
    Command command = commandStack.get(undoRedoPointer);
    command.unExecute();
    undoRedoPointer--;
}

private void redo()
{
    if(undoRedoPointer == commandStack.size() - 1)
        return;
    undoRedoPointer++;
    Command command = commandStack.get(undoRedoPointer);
    command.execute();
}

Conclusion:

What makes this design powerful is the fact that you can add as many commands as you like (by extending the Command class) e.g., RemoveCommand, UpdateCommand and so on. Moreover, the same pattern is applicable to any type of object, making the design reusable and modifiable across different use cases.

Menelaos Kotsollaris
  • 5,776
  • 9
  • 54
  • 68
  • How would you go about limiting the number of undo/redo steps? It's not possible to size a stack. – Atlas2k Nov 24 '17 at 23:30
  • @Atlas2k you can have a threshold (e.g., `int threshhold = 30`) and then remove all the "older" commands based on the current stack size. For instance, if you call `insertCommand()` and your `commandStack.size()` is bigger than 30, then you remove the first element (`commandStack.remove(0)`). The main idea is to limit your stack to a certain threshold size. Yes, more complex use-case, but definitely doable :) – Menelaos Kotsollaris Nov 25 '17 at 00:32
  • I followed this to set my max stack size: http://ntsblog.homedev.com.au/index.php/2010/05/06/c-stack-with-maximum-limit/ – Atlas2k Nov 25 '17 at 00:35
1

You have to define undo(), redo() operations along with execute() in Command interface itself.

example:

interface Command {

    void execute() ;

    void undo() ;

    void redo() ;
}

Define a State in your ConcreteCommand class. Depending on current State after execute() method, you have to decide whether command should be added to Undo Stack or Redo Stack and take decision accordingly.

Have a look at this undo-redo command article for better understanding.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

I would try to create an Action class, with a AddElementAction class inheriting off Action. AddElementAction could have a Do() and Undo() method which would add/remove elements accordingly. You can then keep two stacks of Actions for undo/redo, and just call Do()/Undo() on the top element before popping it.

nolegs
  • 608
  • 4
  • 11
  • See [`javax.swing.undo.UndoManager`](http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/UndoManager.html) – Nate W. Jul 17 '12 at 20:30