SWT Designer 实现了强大SWT/JFace 可视化编辑功能,在Graphical Editor下画出来的图形效果很好,下面就来尝试用Draw2D里面的Figure来模拟一下SWT里常见的控件。
从Button开始吧。
图形编辑的时候,Button看起来就是一个凸起的图形,加上一个字符描述。
图中第二个就是真实的Button,而第一个是用Draw2D 绘制的,并没有处理按键行为,仅仅是模拟外观,在图形编辑时就够了。
public class ButtonFigure extends Label{
public ButtonFigure(){
this("");
}
public ButtonFigure(String text){
super(text);
//LineBorder lineBorder = new LineBorder();
//lineBorder.setColor(ResourceConstants.BORDER_COLOR);
//Choose which style is better, flat or 3D
SimpleRaisedBorder border = new SimpleRaisedBorder();
setBorder(border);
}
}
代码很简单,不用解释了。画出来的效果与上图中一致。
如果定义Button中的文字位置,有可能为LEFT、CENTER、RIGHT,这时候就要重新绘制Button上的文字了。
/* (non-Javadoc)
* @see org.eclipse.draw2d.Label#paintFigure(org.eclipse.draw2d.Graphics)
*/
@Override
protected void paintFigure(Graphics graphics) {
Dimension size = FigureUtilities.getTextExtents(getText(), graphics
.getFont());
Rectangle bounds = getBounds();
graphics.drawText(getText(), bounds.x + 3, bounds.y
+ (bounds.height - size.height) / 2);
}
代码为在LEFT位置绘制文字,效果为:
如果需要在RIGHT位置,修改
graphics.drawText(getText(), bounds.x + 3, bounds.y
+ (bounds.height - size.height) / 2);
中对应参数就就行了。