JTextArea Document Listener updating text
-
12-06-2021 - |
Question
I have a JTextArea and I'd like to listen when the user pastes text in the JtextArea. Specifically, I'd like to do the following:
Get the text they pasted, remove whitespaces, and replace the JTextArea text with the edited text without spaces (rather than the original text the user pasted).
How can I do this using a DocumentListener, and avoiding java.lang.UnsupportedOperationException: Not supported yet.
, which comes as a result of the following code:
public void insertUpdate(DocumentEvent de) {
final String replace = jTextArea1.getText().replaceAll("\\s","");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jTextArea1.setText(replace);
}
});
}
Solution
I haven't any issue with method insertUpdate(DocumentEvent documentEvent)
, sure JTextArea can accepting only chars input, if you'll have an issue use JEditorPane, there you can importing another Java AWT and Swing Objects too
code example
private DocumentListener docListener = new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
@Override
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
//your code
}
};
for replacing inserted characters you have to add DocumentFilter
OTHER TIPS
If you would like remove white character use \S or \s
in regexp. If you woudlike to remove only space you may do it in this same way. Read more about regexp: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html