tags:

views:

599

answers:

1

I am calling com.google.gwt.user.client.ui.TextArea.setText(myText) to set the content. After that I call setCursorPosition(myText.length()) to get the cursor to the end. This works well.

When myText has more lines then the text area can display at once, it shows a scroll bar. But it does not scroll to the cursor position. Even worse - it scrolls to the top.

How can I scroll the GWT TextArea to the cursor position? I realy need the cursor position, not the bottom of the TextArea. A JSNI workaround would be ok too.

+1  A: 

Try adding this after setting the cursor position:

textAreaToScroll.getElement().setScrollTop(textAreaToScroll.getElement().getScrollHeight());

This will scroll the element to the bottom.

EDIT:

To scroll to the any cursor position there is (as far as I know) no easy way to do so. I don't think there is any way to ask the browser wich line the cursor is on. I just got an idea for something that may work (haven't actually tested it) to guess a rough estimate of how long to scroll.

int cursorPos = textAreaToScroll.getCursorPos();
long offsetRatio = cursorPos / textAreaToScroll.getText().length(); 
//gives 0.0 to 1.0
offsetRatio += someMagicNumber; // -0.1 maybe?
// Depending on the font you may need to adjust the magic number
// to adjust the ratio if it scrolls to far or to short.
offsetRatio = offsetRatio>0.0 ? offsetRatio : 0; //make sure 
//we don't get negative ratios 
//(negative values may crash some browsers while others ignore it) 
textAreaToScroll.getElement().setScrollTop(
     textAreaToScroll.getElement().getScrollHeight() * offsetRatio );

This may scroll the roughly the desired distance. Note, this assumes each line is filled about the same amount since it uses the cursor position divided by the length of the text and not the number of lines (wich is hard to calculate). Manual newlines will skew this estimate, and proportional fonts will allso make it less accurate.

You'll probably need to adjust the ratio so that it scrolls sligtly too short rather than too far since the cursor will still be visible if it's slightly below the top of the text area.

As I said I haven't actually tested this, I may have inverted the logic and other subtle bugs.

Stein G. Strindhaug
This code scrolls the TextArea to the bottom, unfortunately not to the cursor position :-(
Witek
If you set the cursor to the end would it not be on the bottom line?
Stein G. Strindhaug
I need a solution, where the TextArea scrolls to the position of the cursor, not to the end. Example: TextArea has 5 lines height. Its text content is 50 lines. The cursor is on line 25. I would like to have a method scrollToCursorPosition() which scrolls to line 25, not to line 50.
Witek
Did my proposed solution work for you?
Stein G. Strindhaug