JTextField has an undo support out of box. It works fine for user interacion, but unfortunately if method setText(String str) is called, that results two UndoableEdits instead of one. So this code looks and feels fine but does not work:
UndoManager undoManager = new UndoManager();
JTextField tf = new JTextField();
tf.setText("initial value");
tf.getDocument().addUndoableEditListener(undoManager);
tf.setText("new value");
undoManager.undo();
System.out.println(tf.getText()); // Prints empty string
undoManager.undo();
System.out.println(tf.getText()); // Prints "initial value" as expected
Can JTextField somehow handle setText() as only one UndoableEdit?
Found a workaround:
not fans of
DragAndDrop
andUndoAndRedo
have to load data to the
UndoManager
and defineUndoAction undoAction = new UndoAction();
the same is possible for simpleGraphics
or e.i.and to create
Swing Action
(add toJButton)
for flushing contens back to theJTextField
Another option is to override Document#replace(...)