撤消 arrayList 中的更改 [英] Undo changes in an arrayList

查看:35
本文介绍了撤消 arrayList 中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为线"的线对象 ArrayList.我制作了自己的线条类来绘制带有一些约束的线条.它涉及在面板中选择两个点,并绘制一条连接这两个点的线.每次创建一行时,它都会添加到行"中.线条绘制在面板中.

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

我想在其中创建一个 UndoAbleEdit,每次我给 undo 时,undo 方法必须恢复到最后一个操作(即创建一行或删除一行).我已经尝试撤销 JTextArea 中的事件,但我不知道如何为 ArrayLists 中的事件更改构建自定义撤销.建议一个这样做的例子.

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.

我真的很抱歉没有将它作为 SSCCE 发布.这是一个巨大的项目,几乎不可能创建一个 SSCCE.

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.

推荐答案

我会创建和存储 Runnable 对象,以便在某些堆栈结构中撤消更改,根据需要弹出和运行它们.例如:

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

这篇关于撤消 arrayList 中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆