Troubleshooting guide

19
1: Creating UIs
Specify the
arrangement of the
objects in the field.
1. Implement layout(). Arrange field data so that you perform the most complex calculations in layout()
instead of in
paint().
2. Within your implementation, perform the following actions:
To calculate the available width and height, invoke Math.min() to return the smaller of the specified
width and height and the preferred width and height of the field.
To set the required dimensions for the field, invoke setExtent(int, int).
Recalculate the pixel layout, cached fonts, and locale strings.
protected void layout(int width, int height) {
_font = getFont();
_labelHeight = _font.getHeight();
_labelWidth = _font.getAdvance(_label);
width = Math.min( width, getPreferredWidth() );
height = Math.min( height, getPreferredHeight() );
setExtent( width, height );
}
The manager of the field invokes layout() to determine how the field arranges its contents in the available space.
Define the preferred
width of a custom
component.
> Implement getPreferredWidth(), using the relative dimensions to make sure that the label does not exceed
the dimensions of the component.
public int getPreferredWidth() {
switch(_shape) {
case TRIANGLE:
if (_labelWidth < _labelHeight) {
return _labelHeight << 2;
} else {
return _labelWidth << 1;
}
case OCTAGON:
if (_labelWidth < _labelHeight) {
return _labelHeight + 4;
} else {
return _labelWidth + 8;
}
case RECTANGLE: default:
return _labelWidth + 8;
}
}
Task Steps