我在Swing应用程序中使用UndoManager
如果在UndoManager上调用undo()redo()addEdit()或其他方法,则最终必须启用或禁用“撤消和重做”按钮。

我找不到对这些方法调用做出反应的方法。似乎没有为此目的实现的观察者或侦听器模式。

并在每次调用UndoManager方法时更新“撤消”和“重做”按钮的enabled属性……这不是最佳实践吗?

一个例子:


编辑>插入-将编辑添加到UndoManager
编辑>剪切-将编辑添加到UndoManager


在这两种情况下,都必须启用“撤消”按钮(如果尚未启用)。
我需要一种方法来对UndoManager中的所有这些更改做出反应!

最佳答案

您可以将侦听器添加到撤消和重做按钮。 UndoManager不知道您要使用哪个Swing组件来撤消或重做。

这是snippet,显示撤消按钮的按钮侦听器。

// Add a listener to the undo button. It attempts to call undo() on the
// UndoManager, then enables/disables the undo/redo buttons as
// appropriate.
undoButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ev) {
    try {
      manager.undo();
    } catch (CannotUndoException ex) {
      ex.printStackTrace();
    } finally {
      updateButtons();
    }
  }
});

  // Method to set the text and state of the undo/redo buttons.
  protected void updateButtons() {
    undoButton.setText(manager.getUndoPresentationName());
    redoButton.setText(manager.getRedoPresentationName());
    undoButton.getParent().validate();
    undoButton.setEnabled(manager.canUndo());
    redoButton.setEnabled(manager.canRedo());
  }

10-08 03:03