Skip to content

Undo/Redo in Swing

As I recall, Swing does have some kind of undo/redo support so after some googling around I have managed to implement it in my SudokuField. Actually I did my own stack and undo redo operations first, but I wanted to learn how is done with built-in support because I suspected it to be a bit more elegant. Turned out to be a bit fuzzy instead , but still the code to use built in support turned to be somewhat shorter (not much actually ).

public class UndoTextField extends JTextField {

    public UndoTextField(){
	
	getDocument().addUndoableEditListener(urm);

	KeyStroke z = KeyStroke.getKeyStroke(KeyEvent.VK_Z,Event.CTRL_MASK);
	KeyStroke y = KeyStroke.getKeyStroke(KeyEvent.VK_Y,Event.CTRL_MASK);

	getKeymap().addActionForKeyStroke(z,new UndoAction());
	getKeymap().addActionForKeyStroke(y,new RedoAction());
    }
    
    class UndoAction extends AbstractAction {
	
	public void actionPerformed(ActionEvent e) {
	    try {
		urm.undo();
	    } catch (CannotUndoException ex) {
	    }
	}
    }
    
    class RedoAction extends AbstractAction {
	
	public void actionPerformed(ActionEvent e) {
	    try {
		urm.redo();
	    } catch (CannotRedoException ex) {
	    }
	}
    }
	
    static UndoManager urm = new UndoManager();
}

UndoManager is static here because it will be shared between all text field components on a Sudoku panel. Achieved behavior is not exactly what I was hoping for; but it is close enough that I am satisfied considered how short code is (I have own implementation since before, but it is a bit messy to adapt, so I will let it out).

Finally here are two applets to illustrate this:

A JTextField with undo/redo stack.

Several JtextFields with shared undo/redo stack.

Use CTRL-Z to undo and CTRL-Y to redo.

Post a Comment

Your email is never published nor shared. Required fields are marked *