views:

720

answers:

6

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

+7  A: 

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
Yuval A
+3  A: 

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.

Guðmundur Bjarni
+1  A: 

Hmmm...

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.

Argelbargel
A: 

Thanks very much it's working but i have the code

Undo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {

            String undo = null;
          try {
              undo = stack.pop();
                String content=tex.getText()+undo;
             tex.setText(content);
          } catch (Exception e) { 
          }

Undo - is the button that make undo func.

tex - is the TextArea

i push the keyTyped Event in the stack but theres is a bug when i wrote :

Waseem

press undo button , i have something like

Waseem meesaW

Waseem
A: 

Ok i solve it

I must push the text in the textArea not the character from the keyboard

thanks guys

Waseem
A: 

can show complete source code using java