Retrieving the Visible Lines in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Retrieving the Visible Lines in a JTextComponent

Demo Code

import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.Utilities;

public class Main {
  public static String getWrappedText(JTextComponent c) {
    int len = c.getDocument().getLength();
    int offset = 0;

    StringBuffer buf = new StringBuffer((int) (len * 1.10));

    try {/*from w w  w .j  a va 2s. c  om*/
      while (offset < len) {
        int end = Utilities.getRowEnd(c, offset);
        if (end < 0) {
          break;
        }

        end = Math.min(end + 1, len);

        String s = c.getDocument().getText(offset, end - offset);
        buf.append(s);

        if (!s.endsWith("\n")) {
          buf.append('\n');
        }
        offset = end;
      }
    } catch (BadLocationException e) {
    }
    return buf.toString();
  }
}

Related Tutorials