3

我有一个带有 JPanel 和用户单击以在面板上绘制形状的按钮的应用程序。您可以为形状着色和调整大小以及在面板中移动它们。我将如何为这样的应用程序实现撤消和重做?我有一个 Actions 类,其中所有操作都实际实现。在这个类中,每个动作都是它自己的类,它扩展了 AbstractAction。我的 Actions 类基本上是一个嵌套类。

例如,这是我的 Actions 课程中的课程之一:

private class RandomAction extends AbstractAction {
  private static final long serialVersionUID = 1L;
  public NewAction(String text, ImageIcon icon, String desc){
            super(text, icon);
            putValue(SHORT_DESCRIPTION, desc);
        }
        public void actionPerformed(ActionEvent e) {

        }
    }

然后,当我创建一个按钮时,我所做的就是:

 randButton = new JButton(Actions.RandomAction);
4

2 回答 2

5

Usually undo/redo functionality is done by implementing a stack. You can implement your own action stack that keeps track of the previous X actions, which you can then just pop off each time the user undos an action. You will probably also need to keep a similar type of structure for the redo functionality. So when an action is popped off the undo stack, it first needs to go unto the redo stack.

If you are using Java and NetBeans (although strictly speaking you do not need to use the NetBeans IDE), you can have a look at the NetBeans Platform (can be downloaded separately). I have not worked with the undo/redo much, but it does provide the functionality.

Personally I would just write a class that wraps any "action" that the user can do, which I see you already have done. Now it is simply a matter of implementing a stack to keep track of those actions, and when one is popped off the undo stack, you need to do the "opposite" of the action. Place the item on a redo stack, so when the user clicks redo, you can simply pop the action off the redo stack and let your application handle it as it normally would have.

于 2010-11-18T05:17:11.860 回答
1

我同意 Nico 的帖子,我会补充一点,可以使用一个堆栈来进行撤消/重做。

几年前在大学里,我正在编写一个数据流图编辑器,它需要完整的撤消/重做功能。我创建了一个抽象的 Action 类,代表任何可能的用户操作(使用 Undo 和 Do 方法),以及一个 ActionStack,它包装了所有已执行操作的列表并维护指向最后执行的操作的指针。撤消操作将指针移到堆栈的下方,而重做则将其向上移动。因此,如果用户执行 10 个动作,堆栈将包含动作 1-10,并且指针指向动作 #10。如果用户随后执行 5 次撤消操作,堆栈上仍有 10 个操作,但指针移回操作 #5。如果用户随后执行一个新动作,则指针上方的所有动作(动作 6-10)将被删除,新动作将被添加到堆栈顶部,并相应地调整指针。

您描述的用户操作听起来并不太复杂,但对于更复杂的操作,您可能希望允许它们由子操作组成。

于 2010-11-18T06:29:13.363 回答