Search
Undo or Redo Item State Changes

Changes to the state of diagram items caused by invoking item methods that change the item's state are not recorded automatically for later undo. To enable undo of these changes, you must explicitly create a ChangeItemCmd instance and add it to the history queue.

The ChangeItemCmd constructor requires a reference to an item as argument and saves the item's initial state to be restored by later undo. Call the ChangeItemCmd.execute method after one or more item's method calls. execute records the final state of the item to be restored by later redo. This allows changes to several properties of an item to be saved within a single record, which can be undone or redone as a single operation:

Java  Copy Code

ShapeNode node = (ShapeNode)diagram.getNodes().get(0);

// save item state
ChangeItemCmd propChange = new ChangeItemCmd(diagram.getNodes().get(0), "Change");

// change properties
node.setText("new text");
node.setBrush(new SolidBrush(Color.blue));
node.setShape(Shape.fromId("Ellipse"));

// add to history
propChange.execute();

You might need to treat changes to several items as an atomic operation. To do so, create a CompositeCmd instance and add the ChangeItemCmd commands to the composite by calling the addSubCmd method:

Java  Copy Code

if (diagram.getSelection().getNodes().size() == 0) return;

// make all changes seem like a single operation by
// putting them in composite Command
CompositeCmd composite = new CompositeCmd(
    diagram, "Change selection");

for (DiagramNode node : diagram.getSelection().getNodes())
{
    ShapeNode shapeNode = (ShapeNode)node;

    // save item state
    ChangeItemCmd propChange = new ChangeItemCmd(shapeNode, "Change");

    // change properties
    shapeNode.setText("new text");
    shapeNode.setBrush(new SolidBrush(Color.blue));

    // add to the composite
    composite.addSubCmd(propChange);
}

// store final state of all contained commands
composite.execute();