Java SWT StyledText, changing the starting line number

652 views Asked by At

I am currently using a StyledText widget to display some "excerpt" of the actual code, such as a method definition within a Java file.

My problem is that the line number shown in my StyledText always start with 1, which is different from the actual line number in the original file. For example, if the original source looks like:

1:  package something;
2:  
3:  public class MyClass {
4:      public void foo() {
5:          // Do something...
6:      }
7:  }

then, when the foo() method is shown in my StyledText widget, I want to show the line numbers starting from 4, not 1.

Is there a way to achieve this? I read through the javadoc, but could not figure out a good way.

1

There are 1 answers

0
Baz On BEST ANSWER

Just change the LineStyleEvent.bulletIndex in the LineStyleListener:

final StyledText text = new StyledText(shell, SWT.NONE);

text.setText("lalala\n\nlalala\n\nlalala\n\nlalala\n\nlalala\n\nlalala\n\n");
text.addLineStyleListener(new LineStyleListener()
{
    @Override
    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);

        // Apply the offset
        e.bulletIndex += YOUR_OFFSET; // I used 3 here
    }
});

Looks like this:

enter image description here