Undo changes in an arrayList

*爱你&永不变心* 提交于 2019-12-06 07:58:21

I suggest you read about the Memento Pattern (http://en.wikipedia.org/wiki/Memento_pattern), then search the web for some code samples that use this pattern.

I would create and store Runnable objects for making undo changes in some stack structure, popping and running them as needed. For your example:

class Board extends JPanel {
    ArrayList lines = new ArrayList();
    Stack<Runnable> undo = new Stack<Runnable>();

    public void placeLine() {
        Point p1, p2;
        JLabel l1, l2;


        final Line line = new Line(p1, p2, l1, l2);
        lines.add(line);
        undo.push(new Runnable() {
            @Override
            public void run() {
                lines.remove(line);
                this.repaint();
            }
        });

        this.repaint();
    }

    public void deleteLine(final Line l) {
        lines.remove(l);
        undo.push(new Runnable() {
            @Override
            public void run() {
                lines.add(l);
            }
        });
    }


    public void undo() {
        undo.pop().run();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!