Building Reusable Java Widgets

An introduction to writing pluggable do-it-yourself widgets for the Java programmer.

Example 3. WindowBar

The window bar is a component needed for the collapsing pane
example below. You click on the window bar and the pane collapses.
Click on it again and it opens up. To keep it simple I will use a
button for the bar, rather than creating a fancy visual bar. The
bar must broadcast events to signal that the pane should collapse
or restore.

3.1. Layout

The layout of this widget is intentionally trivial, to keep
the example simple.

Your listener defines the two methods invoked when the pane
switch event occurs. In this case it is
restore and collapse.

3.4. Event Multicaster

The multicaster is very similar as well. Just as in the
e-mail example, you must create the add and
remove methods that accept pane switch
listeners as arguments. Then create the
collapse and restore
methods. Note that you do not need to create a new multicaster for
each event class you create. You may choose to have a single
multicaster class for all of your widgets. I have chosen to combine
the events from both examples into one multicaster class. See
Listing 4 for details.

3.4. Hooking it Up

Finally, we need to complete the WindowBar widget. This
widget will simply change its text from “collapse” to “restore”
and back again when clicked. In addition it sends the corresponding
event. Take a look at Listing 6 to
see how it's done.

3.6. Exercises for the Reader

A visual window
bar: Create a subclass of WindowBar that renders itself
graphically, instead of as a button. Read up on mouse listeners and
mouse events; you will need to listen for them.

A more complete window
bar: Consider additional actions such as maximize,
close, etc. What classes change and in what way?

Example 4. Collapsing Pane

The collapsing pane widget is a container containing exactly
one component. It provides a window bar across the top, and the
contained component takes up the rest of the area. When the bar is
clicked, the widget collapses to display just the window bar. When
the bar is clicked again, the component is restored. This widget
does not need to generate events. However, it does need to listen
for events from the window bar and take action based on
them.

4.1. Layout

The CollapsingPane class is a subclass of Panel. I install
BorderLayout as its layout manager. The component that will be
collapsible is installed in the center area, and the window bar is
installed in the north.