ComboBox是SWT中很常见的空间,在Draw2D里我们又得自己去实现它。
SWT Designer中的效果很好,我们就参考它来实现ComboBox。
先看看效果:
拆分一下,Combo主要为两部分:左边的输入选择栏和右边的箭头式按钮。右边的按钮又是一个图片了,而左边的文字,直接绘制上去得了。
ComboBoxFigure.java:
public class ComboBoxFigure extends Label {
private static final Image IMAGE = createImage("icons/combobox.gif");
private static Image createImage(String name) {
InputStream stream = ComboBoxFigure.class.getResourceAsStream(name);
Image image = new Image(null, stream);
try {
stream.close();
} catch (IOException ioe) {
}
return image;
}
public ComboBoxFigure() {
this("");
}
public ComboBoxFigure(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);
graphics.drawImage(IMAGE, bound.x + bound.width - IMAGE.getBounds().width, bound.y + 2);
}
/* (non-Javadoc)
* @see org.eclipse.draw2d.Label#setText(java.lang.String)
*/
public void setText(String s) {
super.setText(s);
repaint();
}
}
几个常量说明一下:
FigureConstants.COMBOBOX_DEFAULT_WIDTH = 100 //Combo的默认宽度
FigureConstants.COMBOBOX_FIXED_HEIGHT = 21//Combo的指定高度
paintFiugure的时候,依然要注意一些细微的调节,这些都是为了使绘制出来的图形更好看一些而已,分析代码可以发现,左边的文字也是绘制上去的。
这里的ComboBox也仅仅是外观上的模拟,并没有一些事件响应和操作处理,在图形编辑器下,我们需要外观上的模拟也就够了。
图片见附件。