Scroll JTextArea Based on the Top Visible Line

I am having trouble with getting a JTextArea to scroll to a certain position in the middle of the text.

I had:

textArea.setCaretPosition(index);

The problem is that that displayed the desired line at the bottom of the visible area. I want to scroll so that it is at the top of the visible area. (My text area is of variable height and width, so I can't just add a constant to make it right.)

I tried this:

textArea.scrollRectToVisible(new Rectangle(0,

textArea.getLineOfOffset(index)

* (textArea.getHeight() / numberOfLines),

1,

1));

and this:

textArea.scrollRectToVisible(new Rectangle(0,

textArea.getLineOfOffset(index)

* textArea.getFont().getSize(),

1,

1));

but neither of those seems to do anything.

[876 byte] By [The.Joy.of.Javaa] at [2007-11-26 17:33:25]
# 1

try {

int offset = textArea.getLineStartOffset(line);

Rectangle view = textArea.modelToView(offset);

view.setSize(textArea.getVisibleRect().getSize());

textArea.scrollRectToVisible(view);

textArea.setCaretPosition(offset);

}

catch (Exception ex) {

ex.printStackTrace();

}

Jasprea at 2007-7-9 0:01:24 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks! That worked great--after I realized that of course I had to put it after I made the text area visible!
The.Joy.of.Javaa at 2007-7-9 0:01:24 > top of Java-index,Desktop,Core GUI APIs...
# 3
of course it worked! ;o)The question is, do you understand why it worked? Sometimes I forget to explain my solutions.
Jasprea at 2007-7-9 0:01:24 > top of Java-index,Desktop,Core GUI APIs...