Because of a lapse in government funding, the information on this website may not be up to date, transactions submitted via the website may not be processed, and the agency may not be able to respond to inquiries until appropriations are enacted. The NIH Clinical Center (the research hospital of NIH) is open. For more details about its operating status, please visit cc.nih.gov. Updates regarding government operating status and resumption of normal operations can be found at OPM.gov.
Java Swing Undo-Redo
Java Swing provides support for undo/redo in applications such as text editors. Bellows are main steps for the implementation:
UndoManager undo_ = new UndoManager();
class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo_.undo(); // undo the editing } catch (CannotUndoException ex) { System.out.println("Unable to undo: " + ex); ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo_.canUndo()) // check if undoable { setEnabled(true); putValue(Action.NAME, undo_.getUndoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Undo"); } } private final static long serialVersionUID = 5L; } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo_.redo(); // redo the edit } catch (CannotRedoException ex) { System.out.println("Unable to redo: " + ex); ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo_.canRedo()) // check if redoable { setEnabled(true); putValue(Action.NAME, undo_.getRedoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Redo"); } } private final static long serialVersionUID = 5L; }
protected class MyUndoableEditListener implements UndoableEditListener { public void undoableEditHappened(UndoableEditEvent e) { // Remember the edit and update the menus. undo_.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } }
undoAction = new UndoAction(); menu.add(undoAction); redoAction = new RedoAction(); menu.add(redoAction);
AbstractDocument doc = (AbstractDocument) textPane.getStyledDocument(); doc.addUndoableEditListener(new MyUndoableEditListener());