Link to home
Start Free TrialLog in
Avatar of csound
csound

asked on

undo/redo

I’m trying to put undo/redo facility to JEditorPne using the example code I found here.
http://javaalmanac.com/egs/javax.swing.undo/UndoText.html


However it does not do the job and it seems to be that the if condition in actionPerformed() always seems to return false.

if (undo.canUndo()) { //always return false;
                        undo.undo();
                    }

Can any one tell me what correction needs to be done in order it to work?
Here is my code
  JEditorPane editor = new JEditorPane();

          //undo redo         
           final UndoManager undo = new UndoManager();
    Document doc = editor.getDocument();
   
    // Listen for undo and redo events
    doc.addUndoableEditListener(new UndoableEditListener() {
        public void undoableEditHappened(UndoableEditEvent evt) {
            undo.addEdit(evt.getEdit());
        }
    });
   
    // Create an undo action and add it to the text component
    editor.getActionMap().put("Undo",
        new AbstractAction("Undo") {
            public void actionPerformed(ActionEvent evt) {
                try {
                             System.out.println("undo()");
                  //  if (undo.canUndo()) {
                        undo.undo();
                       
                             
                 
                 //   }
                } catch (CannotUndoException e) {
                      e.printStackTrace();
                }
            }
       });
       
          // Bind the undo action to ctl-Z
    editor.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK), "Undo");
   
    // Create a redo action and add it to the text component
    editor.getActionMap().put("Redo",
        new AbstractAction("Redo") {
            public void actionPerformed(ActionEvent evt) {
                try {
                          
                        System.out.println("redo()");
                //    if (undo.canRedo()) {
                        undo.redo();
                       
                   
                 //   }
                } catch (CannotRedoException e) {
                      e.printStackTrace();
                }
            }
        });

   
// Bind the redo action to ctl-Y
    editor.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK), "Redo");

Avatar of aozarov
aozarov

Are you sure this method:
public void undoableEditHappened(UndoableEditEvent evt) {
            undo.addEdit(evt.getEdit());
        }
get called...?
Avatar of csound

ASKER

actually it does not get called at all...
do you know how should it be?
ASKER CERTIFIED SOLUTION
Avatar of aozarov
aozarov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial