Undo changes in an arrayList

落花浮王杯 提交于 2019-12-22 20:14:20

问题


I've an ArrayList of Line Objects called 'lines'. I made my own line class to draw lines with some constraints. It involves selecting two points in a panel and a line is drawn connecting the two points. Everytime a line is created, it is added to the 'lines'. The lines are drawn in a panel.

The paint function in my panel looks like this:

   public void paintComponent(Graphics g){      

       super.paintComponent(g);

       for(final Line r:lines){

            r.paint((Graphics2D)g);

       }
    }

And everytime two points are clicked on the panel, a new line is created.

class Board extends JPanel{

 public void placeLine(){
  Point p1,p2;
  JLabel l1,l2;
  ...
  lines.add(new Line(p1,p2,l1,l2));
  this.repaint();
 }
 public void deleteLine(Line l){
  lines.remove(l);
 }
}

I want to create an UndoAbleEdit in this, and everytime i give undo, the undo method must revert to the last action(i.e.creating a line or deleting a line). I've tried undo for events in JTextArea but i couldn't figure out how to build a custom undo for event changes in ArrayLists. Suggest an example for doing this.

And i'm really sorry for not posting it as an SSCCE.. It is a huge project and it is almost impossible to create an SSCCE.


回答1:


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.




回答2:


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();
    }
}


来源:https://stackoverflow.com/questions/10070345/undo-changes-in-an-arraylist

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