Painter
can be used to draw on components backgrounds.
The use of this interface allows reuse of a background Painter
for various
components.
A simple example of a background painter is shown here to draw a circle background:
Painter p = new Painter(cmp) {
public void paint(Graphics g, Rectangle rect) {
boolean antiAliased = g.isAntiAliased();
g.setAntiAliased(true);
int r = Math.min(rect.getWidth(), rect.getHeight())/2;
int x = rect.getX() + rect.getWidth()/2 - r;
int y = rect.getY() + rect.getHeight()/2 - r;
switch (style) {
case CircleButtonStrokedDark:
case CircleButtonStrokedLight: {
if (cmp.getStyle().getBgTransparency() != 0) {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha <0) {
alpha = 0xff;
}
g.setColor(cmp.getStyle().getBgColor());
g.setAlpha(alpha);
g.fillArc(x, y, 2*r-1, 2*r-1, 0, 360);
g.setAlpha(0xff);
}
g.setColor(cmp.getStyle().getFgColor());
g.drawArc(x, y, 2*r-1, 2*r-1, 0, 360);
break;
}
case CircleButtonFilledDark:
case CircleButtonFilledLight:
case CircleButtonTransparentDark:
case CircleButtonTransparentLight: {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha < 0) {
alpha = 0xff;
}
g.setAlpha(alpha);
g.setColor(cmp.getStyle().getBgColor());
g.fillArc(x, y, 2*r, 2*r, 0, 360);
g.setAlpha(0xff);
break;
}
}
g.setAntiAliased(antiAliased);
}
};
cmp.getAllStyles().setBgPainter(p);
Painters can also be used to draw the glasspane which is layered on top of the form.
The example shows a glasspane running on top of a field to show a validation hint,
notice that for real world usage you should probably look into Validator
.
Also notice that this example uses the shorter Java 8 lambda syntax to represent the glasspane.
Form hi = new Form("Glass Pane", new BoxLayout(BoxLayout.Y_AXIS));
Style s = UIManager.getInstance().getComponentStyle("Label");
s.setFgColor(0xff0000);
s.setBgTransparency(0);
Image warningImage = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s).toImage();
TextField tf1 = new TextField("My Field");
tf1.getAllStyles().setMarginUnit(Style.UNIT_TYPE_DIPS);
tf1.getAllStyles().setMargin(5, 5, 5, 5);
hi.add(tf1);
hi.setGlassPane((g, rect) -> {
int x = tf1.getAbsoluteX() + tf1.getWidth();
int y = tf1.getAbsoluteY();
x -= warningImage.getWidth() / 2;
y += (tf1.getHeight() / 2 - warningImage.getHeight() / 2);
g.drawImage(warningImage, x, y);
});
hi.show();