I want to create a Swing JTextPane that takes action when the user types text into it. But I also want to be able to alter the text in that pane without it treating that alteration as a user typing. How can I do this?
Asked
Active
Viewed 197 times
3
![](../../users/profiles/1133011.webp)
David Kroukamp
- 34,930
- 13
- 72
- 130
![](../../users/profiles/1888843.webp)
Jono Matthews
- 31
- 1
-
3You could listen for `KeyEvents` and only look at the document then. Or you could put up an internal flag telling your listener that it is currently being modified by a programm and not by a user. – mercutio Dec 09 '12 at 03:36
-
4I like @mercutio's second idea better. KeyEvents can be deceiving, especially since there are other non-key ways to interact with a text component. – Hovercraft Full Of Eels Dec 09 '12 at 03:55
-
*alter the text in that pane without it treating that alteration as a user typing* I dont think that is possible via API... with that being said maybe your codes logic is a bit skewed, as you should fix the entire text they input and than you would reset that text via `insertString(..)` for example, that call would of course fire `insertUpdate(..)`, but because the text was previously changed to match constraints, it should pass through all validations thus no alterations being done i.e `insertString(..)` is not called IMO. Something similar to this: http://stackoverflow.com/a/13721186/1133011 – David Kroukamp Dec 09 '12 at 08:21
1 Answers
1
If you don't let update events fire, then chances are that your UI won't get updated either, depending on the actual implementation. So I agree that you might be better off by talking to the event handler, letting it know that the next alteration is going to be a programmatic change. Something like this:
try {
listener.setProgrammaticChange(true);
// change document
}
finally {
listener.setProgrammaticChange(false);
}
![](../../users/profiles/1468366.webp)
MvG
- 51,562
- 13
- 126
- 251