Ayman
Ayman

Reputation: 11585

JEditorPane get position for character at line and column number

How to get the Position, for use with setCaret from a given line and column?

The component has a single font and it is monospaced. Most other answers I've seen are for determining the line and column number for a given position. I'm looking for the reverse of this.

I did see JTextComponent.viewToModel but couldn't get far. There has to be a quick way? :-)

Upvotes: 1

Views: 718

Answers (2)

camickr
camickr

Reputation: 324167

Use the Element structure of the Document to get the starting offset of the specified line and then just add the column that you want to position the Caret at:

Element root = component.getDocument().getDefaultRootElement();
int startOfLineOffset = root.getElement( line - 1 ).getStartOffset();
component.setCaretPosition( startOfLineOffset  + column);

Upvotes: 3

StanislavL
StanislavL

Reputation: 57421

You can get row height and char width. Use modelToView() returned rectangle to get row height and x difference for position 0 and position 1 to get x. Then use viewToModel() passing y=rowHeight*rowNumber and x=charWidth*colNumber

Upvotes: 2

Related Questions