I'm trying to get my first UndoManager work, but I got a problem with the prototype. I don't understand why the following code provides only one single undo.
When I change the text, click undo and change the text again, another undo won't do anything. Where is the catch?
import java.awt.*;
import javax.swing.*;
public class IComeUndone
{
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea textArea = new JTextArea(20, 40);
textArea.setText("Back here");
f.add(textArea);
final UndoManager undoManager = new UndoManager();
textArea.getDocument().addUndoableEditListener(undoManager);
undoManager.setLimit(1000);
JButton undoB = new JButton("Undo");
undoB.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
undoManager.end();
if(undoManager.canUndo())
{
undoManager.undo();
}
textArea.requestFocus();
}
});
f.add(undoB, BorderLayout.PAGE_END);
f.pack();
f.setVisible(true);
}
}
Update:
When I comment out the undoManager.end();
line, it works fine, but each click on undo does only undo one single edit, like one typed letter. I wanted to undo a group of single edits, so that the undoManager.end();
makes sense at this point. But I can't restart the tracking of single edits after undo has been clicked the first time. (Hope you can understand)