SWT的PaintListener

以前很少用到这个类(org.eclipse.swt.events.PaintListener),利用它可以用来在control上画一些东西,基本方法是在control上 addPaintListener()一个PaintListener,然后在这个listener里做具体的画图工作,listener在control需要绘制的时候调用。

下面例子代码用来在一个composite的中央绘制一行文字。

package com.test;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test3 {

    
public static void main(String[] args) {
        Display display 
= new Display();
        Shell shell 
= new Shell(display);
        shell.setLayout(
new FillLayout());
        
final Button button = new Button(shell, SWT.PUSH);
        button.setText(
"This is a button");
        
final Composite comp2 = new Composite(shell, SWT.BORDER);
        comp2.addPaintListener(
new PaintListener() {
            
public void paintControl(PaintEvent e) {
                String text 
= "This is a composite";
                Rectangle area 
= comp2.getClientArea();//client area
                int tw = calcTextWidth(e.gc, text);//text width
                int th = e.gc.getFontMetrics().getHeight();//text height
                Rectangle textArea = new Rectangle(area.x + (area.width - tw) / 2,
                        area.y 
+ (area.height - th) / 2
                        tw,
                        th);
//centerized text area
                e.gc.drawString(text, textArea.x, textArea.y);
                e.gc.drawRectangle(textArea);
            }


            
private int calcTextWidth(GC gc, String text) {
                
int stWidth = 0;
                
for (int i = 0; i < text.length(); i++{
                    
char c = text.charAt(i);
                    stWidth 
+= gc.getAdvanceWidth(c);
                }

                
return stWidth;
            }

        }
);
        shell.open();
        
while (!shell.isDisposed()) {
            
if (!display.readAndDispatch())
                display.sleep();
        }

        display.dispose();
    }

}

运行结果如下图:

posted @ 2005-09-23 17:01  八进制  阅读(4439)  评论(0编辑  收藏  举报

博客已搬家:bjzhanghao.com