Java tutorial
//package com.java2s; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.Utilities; public class Main { /** * Get the string from the passed in textComponent representing the text displayed by the * component with all the soft new lines (added in from text wrapping) added in. * * @param c * @return * 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(); } }