I need some help in Undo function in Java
I write a Text Editor with Java , and I want to add Undo function to it
but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s) I need some hints or links . Thanks
Assuming you are using Java 5, Stack is a generic class. You can instantiate it according to the objects it should hold.
You can then use:
Stack<String> stack = new Stack<String>(); String string = "someString"; stack.push(string);
Also note that in the case you are using Java 1.4 or below, you can still push String objects into the stack. Only that you will need to explicitly downcast them when you pop() them out, like so:
Stack stack = new Stack(); String string = "someString"; stack.push(string); String popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted
The "data structure", which in fact is a pattern, is called Memento. It is helpful when you need to store multiple states and have the option of going back to a previous state. For efficient data storage of the states depends on what kind of a text editor you are doing, if can do some formatting, then take a look at the Flyweight pattern.
Seems a little like a case of RTFM to me ;-)
If you're using Java 1.4.2 you'll simply have to explicitly cast your objects when you get them from your stack:
Command cmd = (Command) stack.pop(); // same for peek() etc.
If you're using Java 1.5, make use of Generics and there will no need for explicit casting.
Ok i solve it
I must push the text in the textArea not the character from the keyboard