观察UndoManager

时间:2012-09-21 16:37:11

标签: java listener observer-pattern

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

我无法找到对这些方法调用做出反应的方法。似乎没有为此目的实现Observer或Listener模式。

每次调用UndoManager方法时都会更新Undo和Redo按钮的enabled属性......这不是最佳做法吗?!

示例:

  • 编辑> insert - 将编辑添加到UndoManager
  • 编辑>剪切 - 为UndoManager添加编辑

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

1 个答案:

答案 0 :(得分:1)

您可以将侦听器添加到撤消和重做按钮。 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());
  }