Hello @[email protected] <[email protected]>,
I don't usually work with the Undo/Redo side of Swing, so today was my
first foray in years. Long story short, it felt a little more primitive
than necessary.
For starters, none of the publilc JTextComponent implementations in the
JDK support undo/redo out of the box! Each one requires your own
implementation. Fine, whatever. We have to add
someJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); for every
JFrame we create, so I can't say this isn't par for the course with Swing.
Regardless, in order to add undo (not even redo!) to a simple JTextField,
one must perform the following steps.
1. final JTextField textBox = new JTextField(...);
2. final UndoManager undoManager = new UndoManager();
3. textBox.getDocument().addUndoableEditListener(undoManager);
4. final Action undoAction = new AbstractAction(){@Override public void
actionPerformed(final ActionEvent event) {undoManager.undo();}};
5. textBox.getInputMap().put(KeyStroke.getKeyStroke("ctrl Z"), "undo");
6. textBox.getActionMap().put("undo", undoAction);
Again, this only implements undo, not even redo. You'd have to redo (heh)
ALL STEPS except step 1! That's kind of rough.
Just wanted to share my experience, in case it helps.
Thank you for your time and consideration.
David Alayachew