-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathUndoStack.java
More file actions
115 lines (100 loc) · 2.04 KB
/
UndoStack.java
File metadata and controls
115 lines (100 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.util.Stack;
/**
* class UndoStack - class for holding chronological changes
*
* @author Dakota Williams
*/
public class UndoStack<E> {
private Stack<E> undoStack;
private Stack<E> redoStack;
/**
* Constructor - initializes the stacks
*/
public UndoStack() {
undoStack = new Stack<E>();
redoStack = new Stack<E>();
}
/**
* pushChange - adds a state to the undo stack
*
* @param state the state to push on
*/
public void pushChange(E state) {
redoStack.clear(); //flush redo stack since history has now changed
undoStack.push(state);
}
/**
* canUndo - determines if it's possible to undo
*
* @return true if possible to undo
*/
public boolean canUndo() {
return !undoStack.empty();
}
/**
* undo - reverts the state back to the previous change
*
* @param state the current state
* @return the previous state
*/
public E undo(E state) {
redoStack.push(state);
E obj = undoStack.pop();
return obj;
}
/**
* canRedo - determines if it's possible to redo
*
* @return true if possible to redo
*/
public boolean canRedo() {
return !redoStack.empty();
}
/**
* redo - reverts the state back to a undone change
*
* @param state the current state
* @return the new state
*/
public E redo(E state) {
undoStack.push(state);
E obj = redoStack.pop();
return obj;
}
/**
* reset - deletes all history
*/
public void reset() {
undoStack.clear();
redoStack.clear();
}
/**
* resetFuture - deletes all future history
*/
public void resetFuture() {
redoStack.clear();
}
/**
* peekUndo - gets the undo without popping
*
* @return the previous state
*/
public E peekUndo() {
return undoStack.peek();
}
/**
* peekRedo - gets the redo without popping
*
* @return the next state
*/
public E peekRedo() {
return redoStack.peek();
}
/**
* print - prints a string representation of the stacks
*/
public void print() {
System.out.println("\nUndo stack: " + undoStack.toString());
System.out.println("Redo stack: " + redoStack.toString());
}
}