gpt4 book ai didi

java - JComponent 上有 UndoManager 和监听器时的 OO 概念

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:57 25 4
gpt4 key购买 nike

当在 Swing 中构建 GUI 时,我总是遇到一个概念问题,以至于我以一种糟糕的方式结束了 hacking。我想知道这方面的良好做法。

让我们举一个简单的例子。

我有一个 JComponent,我想在其上实现撤消/重做操作,以及一些添加/删除其他组件的操作。所以,我会开始写:

public class MyComponent extends JComponent {
private UndoManager undo = new UndoManager();
public void addComponent(JComponent comp) {
this.add(comp);//Add the component to the view
undo.addEdit(new ComponentAddedEdit(comp));//make this action undoable
fireComponentAdded(comp);//warn the listeners that the action occured
}
}

然后开始问题。在我的 ComponentAddedEdit 中,我会想到类似的东西:

public class ComponentAddedEdit extends AbstractUndoableEdit {
private final JComponent comp;
public ComponentAddedEdit(JComponent comp) {this.comp = comp;}
@Override
public void undo() throws CannotUndoException {
MyComponent.this.removeComponent(comp);
}
@Override
public void redo() throws CannotRedoException {
MyComponent.this.addComponent(comp);
}
}

当然,它不起作用,因为重做操作将为 UndoManager 创建一个新的编辑。所以我需要创建一个像这样的新方法:

public void addComponentNoUndo() {
this.add(comp);//Add the component to the view
fireComponentAdded(comp);//warn the listeners that the action occured
}

最后,对于“add”操作,我最终得到了 3 个名称相似的方法:addaddComponentaddComponentNoUndo。如果我有更多的 Action ,更复杂的 Action ,它会变得非常困惑。那么你会怎么做呢?

最佳答案

我不太喜欢 swing,所以我可能不会给你具体的实现答案,但请参阅此 tutorial on memento pattern .

您肯定需要根据您的需求进行定制,但我认为这是正确的方法。

尝试编写自己的“状态”类,而不是简单地使用字符串。

如果您想撤消某些操作,请加载旧状态。如果您不希望用户能够撤消某些操作,只需不加载之前的状态即可,告诉用户这是不可能的。考虑添加一个 boolean 标志“undoable”到你的“state”类。

编辑

类似的东西

class state extends JComponent {

private boolean undoable;
private JComponent toSave;

public state (boolean undoable, JComponent toSave, ...) {
this.undoable = undoable;
this.toSave = toSave;
...
}
...
}

关于java - JComponent 上有 UndoManager 和监听器时的 OO 概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34333192/

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