Java SWT show Line numbers for StyledText

java, line, numbers, styledtext, swt

Solution

The key is org.eclipse.swt.custom.Bullet. It's basically a symbol (or in our case a number) you can add to the beginning of a line.

//text is your StyledText
text.addLineStyleListener(new LineStyleListener()
{
    public void lineGetStyle(LineStyleEvent e)
    {
        //Set the line number
        e.bulletIndex = text.getLineAtOffset(e.lineOffset);

        //Set the style, 12 pixles wide for each digit
        StyleRange style = new StyleRange();
        style.metrics = new GlyphMetrics(0, 0, Integer.toString(text.getLineCount()+1).length()*12);

        //Create and set the bullet
        e.bullet = new Bullet(ST.BULLET_NUMBER,style);
    }
});

Problem

I was wondering if there is a straightforward way to display line numbers with `StyledText` text field - even if lines are wrapped. I'm using it in my application and if content gets to big, some line numbers would be nice. Thank you.

Original source