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);
}
}
}
The Colors Bean displays a colored object within a frame. The color of the component is
determined by the private Color variable color, and its shape is determined by the private
boolean variable rectangular. The constructor defines an anonymous inner class that extends
MouseAdapter and overrides its mousePressed( ) method. The change( ) method is invoked
in response to mouse presses. It selects a random color and then repaints the component. The
getRectangular( ) and setRectangular( ) methods provide access to the one property of this
Bean. The change( ) method calls randomColor( ) to choose a color and then calls repaint( )
to make the change visible. Notice that the paint( ) method uses the rectangular and color
variables to determine how to present the Bean.
The next class is ColorsBeanInfo. It is a subclass of SimpleBeanInfo that provides explicit
information about Colors. It overrides getPropertyDescriptors( ) in order to designate which
properties are presented to a Bean user. In this case, the only property exposed is rectangular.
The method creates and returns a PropertyDescriptor object for the rectangular property. The
PropertyDescriptor constructor that is used is shown here:
PropertyDescriptor(String property, Class<?> beanCls)
throws IntrospectionException
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home