Exposing a Bean's Properties
The users of a bean may be given read and/or write access to the properties (data
values) of a bean via 'get' and 'set' (accessor and mutator) methods respectively that
are built into the design of the bean. For a property with name prop of type T , the
corresponding methods will have the following signatures:
public T getProp()
public void setProp(T value)
For example, if users of a bean with a property called colour are to be given
read-and-write access to this property, then the bean designer would provide
methods getColour and setColour as part of the bean's interface. If only read access
is to be granted, then only the former method would be made available. If prop is a
Boolean property, then method name isProp is used instead of getProp (and returns
a boolean value, of course).
For purposes of illustration, we'll expose properties delay and imageName of our
animation bean, granting read-and-write access to both of these properties.
Implementation of methods getDelay , setDelay and getImageName is reasonably
straightforward, but the implementation of method setI mageName requires the
erasing of the old image and the loading of frames for the new animation. Using
our previous program ( AnimBean1.java ) as our starting point, the additions and
modifi cations required to expose properties delay and imageName are shown in
bold text below.
In order for this program to work, the GIF fi les used in any animation sequence
must have names comprising a fi xed string followed by an integer, with integer
values covering the range 0…n−1 for a sequence of n frames. (E.g., cartoon0 ,
cartoon1 ,…, cartoon5 for a sequence of six frames.)
public class AnimBean 2 extends JPanel
private ImageIcon image;
private String imageName = "juggler";
private String oldImage = "juggler";
//Need to save old image name so that code can
//compare this with current image name and determine
//whether user has changed the image name.