javaeclipse-pluginswtstyledtext

SWT StyledText - auto highlight (or autoselect)


I am using SWT StyledText to populate the responses to my queries in my plugin. I learnt how to autoscroll to the bottom, but couldn't figure out the correct way to auto select the last entry. I have managed to do this in an un-optimized way, i.e updating the background of all the previous lines to white and then highlighting the latest added line, but there has to be a better way to do this.

Here is my code:

rspST.append(rsp + "\n");     ** //<--- Appending the new response to the styledText **
rspST.setTopIndex(rspST.getLineCount() - 1);     ** //<-- Scroll to bottom**

for(int i=0; i<rspST.getLineCount() - 2; i++)   ** //Setting the background of previous entries to white**
{
    rspST.setLineBackground(i, 1,rspST.getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
rspST.setLineBackground(rspST.getLineCount() - 2,
    1,rspST.getDisplay().getSystemColor(SWT.COLOR_GRAY));    ** Setting the background of the last line added to gray**

Thanks!


Solution

  • This code will select the last line added by clicking the Button:

    private static int lineNr = 0;
    
    public static void main(String[] args)
    {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(1, false));
    
        final StyledText text = new StyledText(shell, SWT.BORDER);
        text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    
        Button button = new Button(shell, SWT.PUSH);
        button.setText("Add new line");
        button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        button.addListener(SWT.Selection, new Listener()
        {
            @Override
            public void handleEvent(Event arg0)
            {
                /* Get the start position of the new text */
                int start = text.getText().length();
    
                /* Create the new line */
                String newText = "Line: " + lineNr++ + "\n";
    
                /* Add it */
                text.append(newText);
    
                /* Determine the end of the new text */
                int end = start + newText.length();
    
                /* Set the selection */
                text.setSelection(start, end);
            }
        });
    
        shell.pack();
        shell.setSize(600, 400);
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
    

    This is what it looks like:

    enter image description here