Chapter 28: Java Beans 855
public boolean getRectangular() {
return rectangular;
}
public void setRectangular(boolean flag) {
this.rectangular = flag;
repaint();
}
public void change() {
color = randomColor();
repaint();
}
private Color randomColor() {
int r = (int)(255*Math.random());
int g = (int)(255*Math.random());
int b = (int)(255*Math.random());
return new Color(r, g, b);
}
public void paint(Graphics g) {
Dimension d = getSize();
int h = d.height;
int w = d.width;
g.setColor(color);
if(rectangular) {
g.fillRect(0, 0, w-1, h-1);
}
else {
g.fillOval(0, 0, w-1, h-1);
}
}
}
TheColorsBean displays a colored object within a frame. The color of the component is
determined by the privateColorvariablecolor, and its shape is determined by the private
booleanvariablerectangular. The constructor defines an anonymous inner class that extends
MouseAdapterand overrides itsmousePressed( )method. Thechange( )method is invoked
in response to mouse presses. It selects a random color and then repaints the component. The
getRectangular( )andsetRectangular( )methods provide access to the one property of this
Bean. Thechange( )method callsrandomColor( )to choose a color and then callsrepaint( )
to make the change visible. Notice that thepaint( )method uses therectangularandcolor
variables to determine how to present the Bean.
The next class isColorsBeanInfo. It is a subclass ofSimpleBeanInfothat provides explicit
information aboutColors. It overridesgetPropertyDescriptors( )in order to designate which
properties are presented to a Bean user. In this case, the only property exposed isrectangular.
The method creates and returns aPropertyDescriptorobject for therectangularproperty. The
PropertyDescriptorconstructor that is used is shown here:
PropertyDescriptor(Stringproperty, Class<?>beanCls)
throws IntrospectionException