How can I determine how many lines are in a TextArea or JTextArea?

Jan Borchers

If you have a JTextArea with a PlainDocument (every child element represents a single ine) then you could do this:

Document doc = mytextarea.getDocument();
Element root = doc.getDefaultRootElement();
int lines = root.getElementCount();

Sandip Chitale adds

In both cases you could create a java.io.StringReader out of the getText() returned text. Wrap it in a java.io.BufferedReader and then read lines using the readLine() API.

You could walk through the String object returned by getText() and look for ' ' char to count the lines.

For JTextArea there is a direct API -

public int getLineCount();

John Zukowski adds

To manually count them:

String text = area.getText();
StringReader reader = new StringReader(text);
LineNumberReader lnr = new LineNumberReader(reader);
while (lnr.readLine() != null);
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact