0

I want to implement undo and redo operation for my paint application.

I created class which extends from jpanel and here i have arraylist to keep all the elements on my jpanel.

This how it works when i add new element (f.e i draw something with pencil tool):

this.elements.add(new PencilElement(this.tool.getPPoint(), this.tool.getCPoint(), this.tool.getColor(), this.tool.getStroke()));

I want to use another arraylist to keep copy of all elements and when i click "undo" button: -->last element from temporary array list would be removed -->content of base arraylist (in this case "elements" arraylist) would be replaced by this temporary arraylist content.

If you have another ideas, please share

Thanks!

Leo
  • 6,480
  • 4
  • 37
  • 52
chris
  • 58
  • 1
  • 8

2 Answers2

0

When you want to make a redo, then you should not delete the last element from the second ArrayList, because you will need it for the redo.

Patricia
  • 2,885
  • 2
  • 26
  • 32
0

Create a stack using Deque (Why should I use Deque over Stack?)

A suggestion is to use a stack for the actions also, so you simply can pop from the ordinary action stack and push on the undo stack, and the other way around when making a redo.

//suggestion for current solution

private Deque<PencilElement> undoStack = new ArrayDeque<PencilElement>();

//whenUndo
undoStack.addFirst(myPencilElement);

//whenRedo
elements.add(undoStack.removeFirst());


//New suggestion
//whenUndo
undoStack.addFirst(elements.removeFirst());

//whenRedo
elements.add(undoStack.removeFirst());

also make sure to disable redo when no actions on the stack

Community
  • 1
  • 1
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75