Author: rwhitcomb Date: Tue Sep 3 21:41:32 2013 New Revision: 1519859 URL: http://svn.apache.org/r1519859 Log: Add convenience methods to TextPane to deal with text-only documents: * "getText()" that returns a String of all the text in the document * "setText()" that constructs a document from the String consisting of a number of paragraphs, one for each line of the string.
These two methods allow TextPane to be used as a drop-in replacement for TextArea, but where additional styling may be needed at some point. Modified: pivot/trunk/wtk/src/org/apache/pivot/wtk/TextPane.java Modified: pivot/trunk/wtk/src/org/apache/pivot/wtk/TextPane.java URL: http://svn.apache.org/viewvc/pivot/trunk/wtk/src/org/apache/pivot/wtk/TextPane.java?rev=1519859&r1=1519858&r2=1519859&view=diff ============================================================================== --- pivot/trunk/wtk/src/org/apache/pivot/wtk/TextPane.java (original) +++ pivot/trunk/wtk/src/org/apache/pivot/wtk/TextPane.java Tue Sep 3 21:41:32 2013 @@ -667,6 +667,49 @@ public class TextPane extends Container // TODO } + private void addToText(StringBuilder text, Element element) { + for (Node node : element) { + if (node instanceof TextNode) { + text.append(((TextNode)node).getCharacters()); + } + else if (node instanceof Element) { + addToText(text, (Element)node); + } + // TODO: anything more that could/should be handled? + } + if (element instanceof Paragraph) { + text.append('\n'); + } + } + + /** + * Convenience method to get all the text from the current document + * into a single string. + * @see #setText + */ + public String getText() { + Document document = getDocument(); + if (document != null && getCharacterCount() != 0) { + StringBuilder text = new StringBuilder(getCharacterCount()); + addToText(text, document); + return text.toString(); + } + return null; + } + + /** + * Convenience method to create a text-only document consisting + * of one paragraph per line of the given text. + */ + public void setText(String text) { + Document document = new Document(); + String[] lines = text.split("\r?\n"); + for (int i = 0; i < lines.length; i++) { + Paragraph paragraph = new Paragraph(lines[i]); + document.add(paragraph); + } + setDocument(document); + } /** * Returns the starting index of the selection.