Wednesday, May 09, 2007

Adding Undo and Redo to a Text Component

The Swing toolkit contains an undo manager that can be added to a Document object to provide undo and redo capabilty. This example adds undo capability to a JTextArea component. The example binds the undo action to control-Z and the redo action to control-Y.
    JTextComponent textcomp = new JTextArea();
    final UndoManager undo = new UndoManager();
    Document doc = textcomp.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
    textcomp.getActionMap().put("Undo",
        new AbstractAction("Undo") {
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undo.canUndo()) {
                        undo.undo();
                    }
                } catch (CannotUndoException e) {
                }
            }
       });
    
    // Bind the undo action to ctl-Z
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
    
    // Create a redo action and add it to the text component
    textcomp.getActionMap().put("Redo",
        new AbstractAction("Redo") {
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undo.canRedo()) {
                        undo.redo();
                    }
                } catch (CannotRedoException e) {
                }
            }
        });
    
    // Bind the redo action to ctl-Y
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");

0 comments:

 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory