Building Beans
Now that you have a feel for how beans look from the user’s perspective, let’s build some. In this section, we will become the Magic Beans Company. We will create some beans, package them for distribution, and use them in NetBeans to build a very simple application. (The complete JAR file, along with all the example code for this chapter, is online at http://oreil.ly/Learn_Java_4E.)
The first thing we’ll remind you of is that absolutely anything can be a bean. Even the following class is a bean, albeit an invisible one:
publicclassTrivialimplementsjava.io.Serializable{}
Of course, this bean isn’t very useful: it doesn’t have any
properties, and it doesn’t do anything. But it’s a bean nonetheless, and
we can drag it into NetBeans as long as we package it correctly. If we
modify this class to extend JComponent,
we suddenly have a graphical bean that be seen in the layout, with lots of
standard Swing properties, such as size and color information:
publicclassTrivialComponentextendsJComponent{}
Next, let’s look at a bean that’s a bit more useful.
The Dial Bean
We created a nifty Dial
component in Chapter 18. What would it take to
turn it into a bean? Surprise: it is already a bean! The Dial has a number of properties that it
exposes in the way prescribed by JavaBeans. A get method retrieves the
value of a property; for example, getValue() retrieves the dial’s current value.
Likewise, a set method, setValue(), modifies the dial’s value. The dial has two other properties, ...