Creating Custom Components
In this chapter and the previous one, we’ve worked with different user interface objects. We’ve used Swing’s impressive repertoire of components as building blocks and extended their functionality, but we haven’t actually created any new components. In this section, we create an entirely new component from scratch, a dial.
Until now, our examples have been fairly self-contained; they
generally know everything about what to do and don’t rely on additional
parts to do processing. Our menu example created a DinnerFrame class that had a menu of dinner
options, but it included all the processing needed to handle the user’s
selections. If we wanted to process the selections differently, we’d have
to modify the class. A true component separates the detection of user
input from the handling of those choices. It lets the user take some
action and then informs other interested parties by emitting
events.
Generating Events
Because we want our new classes to be components, they should communicate the way components communicate: by generating event objects and sending those events to listeners. So far, we’ve written a lot of code that listened for events but haven’t seen an example that generated its own custom events.
Generating events sounds like it might be difficult, but it isn’t.
You can either create new kinds of events by subclassing java.util.EventObject, or use one of the standard event types. In either case, you just need to allow registration of listeners for ...