3

Is there a reliable way to calculate how is a string divided into rows in JTextArea?

I have a JTextArea with fixed width and when it gets filled, a new row is added and it expands vertically.

Now, I need to know exactly which characters are in which row. I could add up single character widths using font metrics, but I don't know if that is reliable, or if there may be a better method.

Is the font metrics "trick" the only way?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Karlovsky120
  • 6,212
  • 8
  • 41
  • 94
  • 2
    This may not be "exactly" the right approach, but you could have look at the [line break](http://docs.oracle.com/javase/tutorial/2d/text/drawmulstring.html) API – MadProgrammer Oct 29 '12 at 22:31
  • You can have a look at my answer to this [question](http://stackoverflow.com/questions/13165617/how-to-determine-which-lines-are-visible-in-scrollable-jtextarea/13168327#13168327). It details how to compute the content of each rows of a JTextArea. – Guillaume Polet Oct 31 '12 at 22:30

2 Answers2

6

All JTextComponents have modelToView(...) and viewToModel(...) methods that can help, but perhaps even better are the methods in the javax.swing.text.Utilities class including getRowStart(...) and getRowEnd(...)

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

modelToView probably doesn't help the OP, because it starts from pixel coordinates. getRowStart is only indirectly useful, because it starts from offset, not row index, and returns an offset. The function that would be most useful here is JTextArea.getLineStartOffset(lineNumber), which returns the offset-from-start-of-text of the beginning of a particular line, and the reverse, JTextArea.getLineOfOffset(offset). (Wish this answer had been here when I stumbled on this page with a similar problem earlier today :-) )

gwideman
  • 2,705
  • 1
  • 24
  • 43