TextField、TextArea也是SWT里常用的控件,接下来我们来模拟它们。
效果图:
上面是TextField,下面是TextArea。
TextField就比较简单了,给Label设一个边框,修改一下背景色,然后绘制一下文字就行了。
TextFieldFigure.java
public class TextFieldFigure extends Label {
public TextFieldFigure() {
this("");
}
public TextFieldFigure(String text) {
super(text);
setMinimumSize(new Dimension(FigureConstants.COMBOBOX_DEFAULT_WIDTH,
FigureConstants.COMBOBOX_FIXED_HEIGHT));
LineBorder lineBorder = new LineBorder();
lineBorder.setColor(ResourceConstants.BORDER_COLOR);
setBorder(lineBorder);
}
/* (non-Javadoc)
* @see org.eclipse.draw2d.Figure#setBounds(org.eclipse.draw2d.geometry.Rectangle)
*/
@Override
public void setBounds(Rectangle rect) {
rect.height = FigureConstants.COMBOBOX_FIXED_HEIGHT;
super.setBounds(rect);
}
/* (non-Javadoc)
* @see org.eclipse.draw2d.Label#paintFigure(org.eclipse.draw2d.Graphics)
*/
@Override
protected void paintFigure(Graphics graphics) {
super.paintFigure(graphics);
Rectangle bound = getBounds();
graphics.setBackgroundColor(ColorConstants.white);
graphics.fillRectangle(bound.x,bound.y, bound.width, bound.height);
graphics.drawText(getText(), bound.x + 2, bound.y + 4);
}
/* (non-Javadoc)
* @see org.eclipse.draw2d.Label#setText(java.lang.String)
*/
@Override
public void setText(String s) {
super.setText(s);
repaint();
}
}
不解释了。
TextAreaFigure就比较麻烦了,主要是右边的滚动条,还需要根据大小来调整,不过自Draw2D,绘制功能尤其强大,有draw就足够实现它了。
右边分为三部分,上下是箭头按钮,图片模拟,中间为滚动区域,填充颜色就行。
TextAreaFigure.java:
public class TextAreaFigure extends Label{
private static final Image UP = createImage("icons/textarea_1.gif");
private static final Image DOWN = createImage("icons/textarea_2.gif");
private static Image createImage(String name) {
InputStream stream = TextAreaFigure.class.getResourceAsStream(name);
Image image = new Image(null, stream);
try {
stream.close();
} catch (IOException ioe) {
}
return image;
}
/**
*
*/
public TextAreaFigure() {
LineBorder lineBorder = new LineBorder();
lineBorder.setColor(ResourceConstants.BORDER_COLOR);
setBorder(lineBorder);
}
/* (non-Javadoc)
* @see org.eclipse.draw2d.Label#paintFigure(org.eclipse.draw2d.Graphics)
*/
@Override
protected void paintFigure(Graphics graphics) {
super.paintFigure(graphics);
Rectangle bound = getBounds();
graphics.setBackgroundColor(ColorConstants.white);
graphics.fillRectangle(FigureUtils.adjustForLineBorder(bound));
graphics.setBackgroundColor(ColorConstants.button);
graphics.fillRectangle(bound.x - UP.getBounds().width + bound.width, bound.y + 2, UP.getBounds().height, bound.height-2);
graphics.drawImage(UP,bound.x - UP.getBounds().width -2 + bound.width, bound.y + 2);
graphics.drawImage(DOWN,bound.x - UP.getBounds().width - 2 + bound.width, bound.y + bound.height - UP.getBounds().height );
}
}
图片见附件。其他的就不解释了。