简体   繁体   中英

Eclipse SWT: How to scroll Text programmatically

I have a Text control on a shell

Text text = new Text(contentComp, SWT.NONE | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);

Its text value would be set by a background thread. For example, the thread may append 1000 lines to the Text. I want to make the Text automatically scroll on the vertical scroll bar while its contents get updated. I tried to set selection in its Modify event listener but it does not work. Any idea how to do that? I cannot use StyledText so there is no setTopIndex method available. Thanks.

This is a workaround that can scroll a (RAP) Text widget by code. However it has limitation. I am not sure whether there is a good solution for this problem. Here is the workaround: Use a ScrolledComposite as the parent of the Text widget.

ScrolledComposite sc = new ScrolledComposite(parent, SWT.NONE|SWT.V_SCROLL);
Text text = new Text(sc, SWT.NONE|SWT.MULTI);

The point is to update the ScrollableComposite#setMinHeight(int) when new data is appended. If this is done in modify listener, then both sc and text would display a scroll bar when text size grows larger than its default on the parent. It looks a little strange but as long as the setMinHeight(int) is updated correctly, calling

sc.setOrigin(sc.getOrigin().x, Integer.MAX_VALUE);

will scroll the text down to the bottom.

Another issue with this workaround is that if you need to dispose controls and re-create them later on with the previously appended data, the auto-scroll won't work any more as text will be resized to fit the sc, thus sc minHeight does not work to scroll.

I wasn't able to get the solution using ScrolledComposite to work. The output was being written to the Text field, but I couldn't see it. It's like the ScrolledComposite was hiding the text.

Instead, I got it to work like this:

Text outputText = new Text(parent, SWT.NONE | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
outputText.addModifyListener(new ModifyListener() {
    @Override
    public void modifyText(ModifyEvent event) {
        Text text = (Text) event.widget;
        // position the cursor after the last character
        text.setSelection(text.getCharCount());
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM