I added an UndoManager to a JTextPane in my application, but I can't get it work:
UndoManager undoManager = new UndoManager();
textpane.getDocument().addUndoableEditListener(undoManager);
When I manually type into the text pane, then try to undo the changes, nothing ever happens undoManager.canUndo()
always returns false.
I also tried another way of adding the manager as follows:
textpane.getDocument().addUndoableEditListener(new UndoableEditListener()
{
@Override
public void undoableEditHappened( UndoableEditEvent e )
{
System.out.println("UndoableEditEvent");
undoMgr.addEdit(e.getEdit());
}
});
With the above code I can see in the output window that the undoableEditHappened( UndoableEditEvent e )
is called once at the start (most likely by a read
call which loads the test file). When I make changes (via keyword) or insertText(...)
calls, there are no further listener calls.
I found some similar questions here in StackOverflow, but the solutions were always alongs the lines that they had custom input methods for the JTextPane
, I don't ... not that I know of.
What might I have overlooked?
I found out why the UndoableEditListener
wasn't triggering.
I was calling JTextPane.read(Reader reader, Object object)
after I had setup the Document
listeners - What I didn't know was that calling the read(...)
method creates and adds a new Document
model to the JTextPane
, which basically removed anything I had previously done to the old Document
.
Solution
Work with the Document
model after calling JTextPane.read(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.