48
Finally, the code draws the button’s label. It first sets the color that’s used to draw the
string, based upon the buttons’s state. That is, for the normal state, the text is set to black,
otherwise, it is set to white to represent the pressed state.
The getFont() method fetches the string’s typeface information. The typeface’s
dimension information is used to center the text string within the button. The
drawString() method draws the button’s label
Scrolling to the end of the RoundButton class code, you see:
/**
* The preferred width of the button.
*/
public int getPreferredWidth() {
Font f = getFont();
int x = f.stringWidth(label) + 10;
return x;
} // end getPreferredWidth
/**
* The preferred height of the button.
*/
public int getPreferredHeight() {
Font f = getFont();
int y = f.getHeight() + 10;
return y;
} // end getPreferredHeight
/**
* Send an action event to the listener.
*/
public void componentActuated() {
dispatchComponentEvent(BUTTON_ACTION_EVENT);
} // end componentActuated
} // end RoundButton
The methods getPreferredWidth() and getPreferredHeight() use
the dimensions of the label string to set the button’s width and height dimensions. The
code adds 10 pixels to the values returned for two reasons. First, it provides a 10-pixel
buffer zone between the round button’s perimeter and the label string. Second, if the label
string is null, a button10 pixels in diameter gets drawn.
The last method, componentActuated(), is called by the LWT when the user
presses the button. This method simply sends an action event to the button’s listener.
As you can see, this code is very basic, other than employing one or two tricks to
implement drawing a circle. The RoundButton class inherits Button’s other features, such
as its response to key events and positioning on screen. In addition, you don’t have to
worry about managing the button’s states (normal, pressed, and focus ownership). The