zoukankan      html  css  js  c++  java
  • 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();
        }

    }

    运行结果如下图:

  • 相关阅读:
    小米路由通过SSH添加静态路由表之后无法跳转的问题
    极路由通过SSH添加静态路由表之后无法跳转的问题
    Linux服务器压测/拷机软件收集
    RabbitMQ整合Spring Booot【消费者补偿幂等问题】
    找不到共享解决办法
    如何一步步设计一款微服务的补偿方案
    Spring Cloud 支付宝支付的流程
    把同事的重复代码清理干净,老板却让我做了回滚?
    [LeetCode] 565. Array Nesting 数组嵌套
    [LeetCode] Out of Boundary Paths 出界的路径
  • 原文地址:https://www.cnblogs.com/bjzhanghao/p/242837.html
Copyright © 2011-2022 走看看