Share the post "Capitalize First Letter Of Each Sentence Of A StyledDocument"
Part of this method is taken from an existing post I published on how to capitalize the first letter of every sentence in a String using Java. I used the same logic to incorporate it into the contents of a Document object.
While I used StyledDocument in the title of my post, this can actually work on other kind of documents like HTMLDocument. You just need to add a DocumentListener to the document object and pass the DocumentEvent as the parameter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
private void formatSentences(DocumentEvent e) { if (e.getDocument() instanceof HTMLDocument && e.getDocument().getLength() > 0) { char[] arr = null; try { arr = document.getText(0, document.getLength()).toCharArray(); } catch (BadLocationException ex) { } if (arr == null) return; // Start off by indicating to capitalize the first letter. boolean cap = true; boolean space_found = true; for (int i = 0; i<arr.length; i++) { if (cap) { if (Character.isWhitespace(arr[i]) || (pilcrowButton.isSelected() && arr[i] == Default.CHAR_UNICODE_DIAMOND)) space_found = true; else { if (space_found && !Character.isUpperCase(arr[i])) { try { dontFormatSentence = true; SimpleAttributeSet attrs = new SimpleAttributeSet(document.getCharacterElement(i).getAttributes()); document.remove(i, 1); document.insertString(i, Character.toString(arr[i]).toUpperCase(), attrs); } catch (BadLocationException ex) { } } cap = false; space_found = false; } } else { if (arr[i] == '.' || arr[i] == '?' || arr[i] == '!') { cap = true; } } } } } |