Q: How can I add Undo and Redo functionality to Qoppa’s PDF components jPDFNotes, jPDFEditor?
The class that provides undo/redo functionality is the UndoManager.
PDFNotesBean provides an implementation which can be referenced with:
PDFNotesBean.getUndoManager() |
The methods which trigger an undo and redo, are respectively:
UndoManager.undo(); UndoManager.redo(); |
Add Undo / Redo in a Menu Bar
To add undo/redo functionality to your application with a menu bar, create menu items as follows:
JMenuItem jmiUndo = new JMenuItem(); jmiUndo.setText("Undo"); jmiUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); jmiUndo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { getPDFNotes().getUndoManager().undo(); } }); |
Add Undo / Redo without Menu Bar
If you want to add undo/redo functionality to your application without using menu items in the menu bar, but only using the keystrokes Ctrl-Z/Ctrl-Y, you need to add an action to the action map of the root pane for the PDFNotesBean, (JFrame, JDialog, ect). Use the action’s key and add it to the root pane’s input map using the selected KeyStroke as the key.
For example, assume the PDFNotesBean is added to a JFrame, “frame1”. The following code demonstrates how to map the undo action to the undo keystroke for the JFrame’s root pane:
String undoKey = "UNDO"; Action undoAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { getPDFNotes().getUndoManager().undo(); } }; KeyStroke undoKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); // frame1 is a JFrame that contains the PDFNotesBean JRootPane rootPane = frame1.getRootPane(); // Add the Action to the root pane's action map rootPane.getActionMap().put(undoKey, undoAction); // Add the KeyStroke to the root pane's input map rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(undoKeyStroke, undoKey); |
Take a Look at our Sample Applications
Undo and Redo functionality is implemented into jPDFNotes Demo Application and jPDFEditor Demo Application. Take a look at these sample applications to see undo / redo in action and look at the demo application code for a full working java sample.