I need help with Undo function in Java

I am writing a text editor from Java and I want to add the Undo function to it

but without UndoManager class, I need to use data structure like Stack or LinkedList, but Stack class in Java uses object parameters like: push (Object o), Not Push (String s) I need hints or links. Thanks to

0


source to share


4 answers


Assuming you are using Java 5, Stack is a generic class. You can instantiate according to the objects it needs to hold.

Then you can use:

Stack<String> stack = new Stack<String>();
String string = "someString";
stack.push(string);

      



Also note that in case you are using Java 1.4 or below you can push String objects onto the stack. Just that you will need to explicitly omit them when you pull them out, like this:

Stack stack = new Stack();
String string = "someString";
stack.push(string);

String popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted

      

+7


source


The "data structure" that is actually a template is called a Memento . This is useful when you need to store multiple states and be able to revert to a previous state. For efficiently storing state data depends on what text editor you are doing, if you can do some formatting, then take a look at Flyweight .



+3


source


Hmmm ...

It seems like something like RTFM to me ;-)

If you're using Java 1.4.2, you just need to explicitly cast your objects when you get them from your stack:

Command cmd = (Command) stack.pop(); // same for peek() etc.

      

If you are using Java 1.5 use Generics and there is no need for explicit casting.

+1


source


Ok i will work it out

I have to press text in textArea and not a character from the keyboard

thanks guys

0


source







All Articles