3

我正在尝试在我正在开发的 Eclipse 插件中的文本编辑器的背景上绘制框。我设法做到了,但问题是当我在文本编辑器中滚动代码时,框也在我滚动的方向上移动。有人知道如何使盒子保持初始位置吗?我的绘图代码是:

<!-- language: lang-java -->

    public class BoxHighLighting {

    protected StyledText boxText;
    private Color bc;
    int startingChar;
    int endingChar; 


    public BoxHighLighting(StyledText boxText, int startingChar, int endingChar, Color color){
        this.boxText = boxText;
        this.startingChar = startingChar;
        this.endingChar = endingChar;
        bc = color;
        setStyledText();
    }

    public void setStyledText() {

        //boxText.getOffsetAtLine(3);

        if (boxText == null)
            return;

        Rectangle r0 = boxText.getClientArea();

        if ((r0.width < 1) || (r0.height < 1)) {
            return;
        }
        int xOffset = this.boxText.getHorizontalPixel();
        int yOffset = this.boxText.getTopPixel();

        Image newImage = new Image(null, r0.width, r0.height);
        GC gc = new GC(newImage);
        Rectangle rec = boxText.getTextBounds(startingChar, endingChar);
        Rectangle editorWin = newImage.getBounds();
        fillRectangle(bc, gc, rec.x, rec.y, editorWin.width, rec.height);
        gc.drawRectangle(rec.x, rec.y, editorWin.width, rec.height);
        Image oldImage = this.boxText.getBackgroundImage();
        this.boxText.setBackgroundImage(newImage);
        if (oldImage != null)
            oldImage.dispose();
        gc.dispose();
    }

    void fillRectangle(Color c, GC gc, int x, int y, int width, int height) {
        if (c == null) {
            return;
        }
         gc.setBackground(c);
                 gc.fillRoundRectangle(x, y, width, height, 5, 5);

    }
}
4

1 回答 1

4

您可以在 ITextEditor StyledText 属性上放置一个绘画侦听器,并检测滚动 x,y 位置何时发生变化,然后在人滚动时重绘您的框

styledText.addPaintListener(new PaintListener() {
    private int oldXOffset = 0;
    private int oldYOffset = 0;

    private boolean offsetMoved(int xOffset, int yOffset) {
       if ((xOffset != oldXOffset) || (yOffset != oldYOffset)) {
         oldXOffset = xOffset;
         oldYOffset = yOffset;
         return true;
       }
       return false;
    }

    public void paintControl(PaintEvent event) {
        if(event.getSource() instanceof StyledText)  {
            StyledText st = (StyledText) event.getSource();
            if(offsetMoved(st.getHorizontalPixel(), st.getTopPixel())) {
                    // do a redraw of the rectangles here!!!!
            }
         }
    }

});

于 2012-05-22T14:19:09.423 回答