gpt4 book ai didi

java - 对 UndoManager 的观察

转载 作者:行者123 更新时间:2023-11-30 11:40:51 32 4
gpt4 key购买 nike

我使用 UndoManager在我的 Swing 应用程序中。如果在 UndoManager 上调用了 undo()redo()addEdit() 或其他方法,Undo 和 Redo 按钮最终必须是启用或禁用。

我找不到对这些方法调用使用react的方法。似乎没有为此目的实现观察者或监听器模式。

并且每次调用 UndoManager 方法时更新 Undo 和 Redo 按钮的启用属性...这不是最佳实践吗?!

一个例子:

  • Edit > insert -- 添加一个 Edit 到 UndoManager
  • Edit > cut -- 添加一个 Edit 到 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());
}

关于java - 对 UndoManager 的观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534559/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com