类ScreenShot:它包含两个ArrayLists(将从旧的ArrayLists创建一个对象并保存在其中然后添加到撤消堆栈)
import java.util.ArrayList;
public class ScreenShot {
private ArrayList<Shapes> shapes;
private ArrayList<Intersection> intersections;
public ArrayList<Shapes> getShapes() {
return shapes;
}
public void setShapes(ArrayList<Shapes> shapes) {
this.shapes = shapes;
}
public ArrayList<Intersection> getIntersections() {
return intersections;
}
public void setIntersections(ArrayList<Intersection> intersections) {
this.intersections = intersections;
}
}
包含撤消重做堆栈的类管理器
public class Manager {
public static Stack<ScreenShot> undoStack = new Stack();
public static Stack<ScreenShot> redoStack = new Stack();
}
包含撤消重做按钮的JFrame:
public class Canvas extends javax.swing.JFrame {
public static ArrayList<Shapes> shapes;
public Canvas() {
initComponents();
}
private void undoActionPerformed(java.awt.event.ActionEvent evt) {
if(Manager.undoStack.isEmpty()==false)
{
ScreenShot temp = Manager.undoStack.pop();
System.out.println(Manager.undoStack.size());
Manager.redoStack.push(temp);
redo.setEnabled(true);
Canvas.prevShapes=(temp.getShapes());
Canvas.intersects.clear();
Canvas.intersects = temp.getIntersections();
if(Manager.undoStack.isEmpty())
undo.setEnabled(false);
}
cc.repaint();
}
private void redoActionPerformed(java.awt.event.ActionEvent evt) {
if(Manager.redoStack.isEmpty()==false)
{undo.setEnabled(true);
ScreenShot temp = Manager.redoStack.pop();
Manager.undoStack.push(temp);
Canvas.prevShapes= temp.getShapes();
Canvas.intersects = temp.getIntersections();
if(Manager.redoStack.isEmpty())
redo.setEnabled(false);
}
cc.repaint();
}
我试图尽可能地缩短守则。所以这里是我遵循Memento设计模式进行撤销和重做技术的基本思路。它正在使用旧的数组列表并正确地将它们保存在堆栈中。但是正在发生的问题是旧的arraylist无论发生什么都不会被清除(如果重要的话,ArrayList是静态的)