即使redo()工作正常,为什么UndoManager.canRedo()返回false?

时间:2020-06-09 19:41:27

标签: java undo-redo redo

我使用Java的undo包中的某些方法得到了矛盾的结果。在我的程序中,我在UndoManager实例上调用canRedo(),该实例返回false。这会让我相信我当时无法重做UndoManager中存储的任何操作。但是,当我尝试时,最后一个未完成的操作已正确重做,并且没有抛出CannotRedoException。在我看来,这种行为是自相矛盾的,我不确定是什么原因造成的。

下面的代码是为这个问题创建的隔离的单线程暂存文件。

import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

class UndoManagerRedoScratch {
    public static void main(String[] args) {
        UndoManager actionList = new UndoManager();
        actionList.addEdit(new SomeUndoableEdit());

        /* See whether SomeUndoableEdit is undoable. */
        try {
            System.out.println("Action can be undone: " + actionList.canUndo());
            actionList.undo();
        } catch (Exception e) {
            System.out.println("Undo failed");
        }

        /* See whether SomeUndoableEdit is redoable. */
        try {
            System.out.println("Action can be redone: " + actionList.canRedo());
            actionList.redo();
        } catch (Exception e) {
            System.out.println("Redo failed");
        }
    }
}

class SomeUndoableEdit extends AbstractUndoableEdit {

    public SomeUndoableEdit() {
        System.out.println("SomeUndoableEdit has been created");
    }

    @Override
    public void undo() throws CannotUndoException {
        System.out.println("SomeUndoableEdit has been undone.");
    }

    @Override
    public void redo() throws CannotRedoException {
        System.out.println("SomeUndoableEdit has been redone.");
    }
}

输出:

SomeUndoableEdit has been created
Action can be undone: true
SomeUndoableEdit has been undone.
Action can be redone: false
SomeUndoableEdit has been redone.

如您所见,redo()成功执行而没有引发CannotRedoException,但canUndo()返回false。同样,这对我来说似乎是矛盾的。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

根据jre中的某些实现,例如javax.swing.undo.StateEdit,您应该在覆盖的方法中首先调用super.undo()super.redo()

因此,您的情况:

class SomeUndoableEdit extends AbstractUndoableEdit {

    public SomeUndoableEdit() {
        System.out.println("SomeUndoableEdit has been created");
    }

    @Override
    public void undo() throws CannotUndoException {
        super.undo();
        System.out.println("SomeUndoableEdit has been undone.");
    }

    @Override
    public void redo() throws CannotRedoException {
        super.redo();
        System.out.println("SomeUndoableEdit has been redone.");
    }
}