Ulrich Scholz
Ulrich Scholz

Reputation: 2111

eclipse ui: setting scrollbar but editor does not follow

In the Eclipse UI, I'd like to set the visible area in an editor. In other words, if the number of lines of my file is larger than the number of lines my editor can show then I want to specify the first shown line. My approach is to set the selection value of the vertical scroll bar. Below you find my code, stripped from irrelevant parts.

The given code sets the scroll bar correctly (the thumb is jumping). The problem is: the area visible in the editor does not reflect this value, it just remains where it was. Upon the next use of the scrollbar, e.g., after clicking the arrow for incrementing the value (scrolling down), the visible area of the editor jumps to the correct position (i.e., the position specified by the thumb).

So, I guess, the editor needs to be notified about the new scroll bar value that I have set, either directly or via a listener. But I could not find the mechanism for it.

public static void update(IWorkbenchWindow w, int someValue)
{
    Display display = w.getWorkbench().getDisplay();
    Scrollable scrollable = (Scrollable) display.getFocusControl();
    ScrollBar vScrollBar = scrollable.getVerticalBar();
    vScrollBar.setSelection(someValue); // between minimal and maximal bound

    // missing call to notify the active editor about the scroll bar value change
} 

Upvotes: 0

Views: 382

Answers (1)

greg-449
greg-449

Reputation: 111142

As you have seen ScrollBar.setSelection does not send a selection event to its listeners.

You would probably be better using code similar to that used by the text editor Goto line code:

IWorkbenchWindow w = ....

IWorkbenchPage page = w.getActivePage();

IEditorPart editor = page.getActiveEditor();

// TODO check editor is actually a text editor
ITextEditorPart textEditor = (ITextEditorPart)editor;

IDocumentProvider provider = textEditor.getDocumentProvider();
IDocument document = provider.getDocument(textEditor.getEditorInput());

try {
  int start = document.getLineOffset(line);

   textEditor.selectAndReveal(start, 0);
} catch (BadLocationException x) {
    // ignore
}

Adapted in part from org.eclipse.ui.texteditor.GotoLineAction

You can get the current visible line from your editor TextViewer or SourceViewer using the getTopIndex() method.

Upvotes: 1

Related Questions