![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e973. Retrieving the Visible Lines in a JTextComponentThere are hard and soft line breaks when viewing the contents of a text component. Hard line breaks are caused by a newline character in the contents. Soft line breaks are a result of word wrapping by the text component. Word wrapping occurs strictly on the display; it does not change the contents (i.e., newlines are not inserted into the contents).This example demonstrates how to retrieve the contents with soft line breaks. The retrieval does not modify the contents; it returns the contents with additional newlines for soft line breaks. Note: // Returns null if comp does not have a size public static String getWrappedText(JTextComponent c) { int len = c.getDocument().getLength(); int offset = 0; // Increase 10% for extra newlines StringBuffer buf = new StringBuffer((int)(len*1.10)); try { while (offset < len) { int end = Utilities.getRowEnd(c, offset); if (end < 0) { break; } // Include the last character on the line end = Math.min(end+1, len); String s = c.getDocument().getText(offset, end-offset); buf.append(s); // Add a newline if s does not have one if (!s.endsWith("\n")) { buf.append('\n'); } offset = end; } } catch (BadLocationException e) { } return buf.toString(); }
e969. Retrieving All the Text from a JTextComponent Efficiently e970. Modifying Text in a JTextComponent e971. Asynchronously Reading the Contents of a Visible JTextComponent e972. Finding Word Boundaries in a JTextComponent e974. Using a Position in a JTextComponent e975. Limiting the Capacity of a JTextComponent e976. Enabling Text-Dragging on a JTextComponent e977. Sharing a Document Between JTextComponents e978. Enumerating All the Views in a JTextComponent
© 2002 Addison-Wesley. |