可旋转的SWT Label

By | 4月 19, 2018

Google一下,SWT GC也可以旋转绘制text,于是用SWT Canvas重写了DirectionLabel。

之前用Draw2d绘制的,我重名为DirectionLabelByDraw2d。
https://github.com/tadckle/rcp/blob/master/rcp3/rcp3.study/src/rcp3/study/composite/DirectionLabelByDraw2d.java


SWT本身的Label不能垂直显示,为了实现垂直显示,可以使用Draw2d手动绘制。我将其封装成一个DirectionLabel,方便重用。

代码:https://github.com/tadckle/rcp/blob/master/rcp3/rcp3.study/src/rcp3/study/composite/DirectionLabel.java

和使用其它SWT控件一样,它接受三个参数:

  • Composite: parent composite.
  • String: label text.
  • int: appearance style.

创建完后,可调用setRotation方法设置旋转度数,参数是一个enum,有四个值可选择:ANGLE_0, ANGLE_90, ANGLE_180, ANGLE_270。不调用此方法,就是不旋转。

DirectionLabel lbl = new DirectionLabel(shell,"This is label message", SWT.BORDER);
lbl.setRotation(Rotation.ANGLE_90);

下面的example展示了四种旋转状态。

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import rcp3.study.composite.DirectionLabel.Rotation;

public class MainUsage {

    public static void main(String[] args) {
        Display display = Display.getDefault();
        Shell shell = new Shell(display);
        GridLayoutFactory.swtDefaults().numColumns(4).applyTo(shell);
                
        String text = "This is label message";
        
        DirectionLabel lbl1 = new DirectionLabel(shell,text, SWT.BORDER);
        lbl1.setRotation(Rotation.ANGLE_0);
        GridDataFactory.swtDefaults().applyTo(lbl1);
        
        DirectionLabel lbl2 = new DirectionLabel(shell,text, SWT.BORDER);
        lbl2.setRotation(Rotation.ANGLE_90);
        GridDataFactory.swtDefaults().applyTo(lbl2);
        
        DirectionLabel lbl3 = new DirectionLabel(shell,text, SWT.BORDER);
        lbl3.setRotation(Rotation.ANGLE_180);
        GridDataFactory.swtDefaults().applyTo(lbl3);
        
        DirectionLabel lbl4 = new DirectionLabel(shell,text, SWT.BORDER);
        lbl4.setRotation(Rotation.ANGLE_270);
        GridDataFactory.swtDefaults().applyTo(lbl4);
        
        lbl4.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_RED));
        lbl4.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_YELLOW));
        lbl4.setFont(FontDescriptor.createFrom(lbl4.getFont())
                .setHeight(9).createFont(Display.getDefault()));
        
        shell.setSize(400, 200);
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        shell.dispose();
        display.dispose();
    }
}

image