Search
Subclassing the Command Class

JDiagram's diagrams can be just a part of the data model of your application, which might already have undo/redo functions implemented for its native data. To integrate JDiagram undo functionality into the application's undo mechanism you have to subclass Command and create classes responsible for changes in your application's data. When a change occurs outside the diagram, it can still be recorded by calling the Diagram's executeCommand method and integrated into JDiagram's command history.

A simpler scenario when you might have to subclass Command is using complex objects as tags. Actions that change these objects cannot be detected and handled automatically by JDiagram. To integrate such an action into the diagram's undo history, you must create a Command instance that knows how to carry out, undo or redo the action.

Command subclasses must implement execute, undo and redo methods. Actions represented by your subclass must be carried out by the executeCommand method of Diagram that invokes executing of the command passed as argument, and then is added to the history queue whose undo and redo methods can be called multiple times later by the UndoManager. Usually you can implement redo as a call to execute, but if the latter is time consuming, its result state can be saved in an instance member and restored by redo.

Do not call the undo and redo methods of your class directly, just implement them and they will be invoked by UndoManager's undo or redo methods when necessary.

The example below shows a simple implementation of Command methods:

Java  Copy Code

class PersonTag
{
    public String Name;
    public String Address;
    // and so on
}

class AddressChangeCmd extends Command
{
    public AddressChangeCmd(PersonTag p, String address)
    {
        super("Address change");

        this.p = p;
        this.oldAddress = p.Address;
        this.newAddress = address;
    }

    @Override
    public void execute(boolean undoEnabled)
    {
        p.Address = newAddress;
    }

    @Override
    public void undo()
    {
        p.Address = oldAddress;
    }

    @Override
    public void redo()
    {
        // undo manager is enabled if Redo is called
        // so pass true for the undoEnabled argument
        execute(true);
    }

    private PersonTag p;
    private String oldAddress;
    private String newAddress;
}

// somewhere in later code
PersonTag tag = (PersonTag)diagram.getActiveItem().getTag();
AddressChangeCmd command = new AddressChangeCmd(tag, "far far away");
diagram.executeCommand(command);