New Control Elements

A window can contain other interactive elements besides scroll bars. For example, a window can contain a button that performs some action when pressed. You can create a new class, PushButton, to represent this type of interactor.

What information does a PushButton store, besides that stored by all Interactor objects? All buttons have a label indicating what they do; a button must retain the text string that it displays as its label. What can a PushButton do? Any button should momentarily reverse its displayed colors to give the user some feedback. Beyond that, the action performed as a result of pressing the button is entirely determined by the client. Just as a scroll bar can be used for different purposes, a button can be used for almost anything. The only thing a button by itself can do is inform its parent window that it has been pressed. To do this, a button sends its parent a new type of event, a PushEvent.

A PushEvent contains a pointer to the button that created it, so the parent window can identify the button that was pressed. It is then up to the parent to perform some function in response.

You could define PushButton as a descendant of Interactor, but it is very similar to the ScrollBar class. Both are always children of windows, and thus contain a pointer to a parent of class Win. You can create an abstract base class for both ScrollBar and PushButton and put the pointer in that class. This new class is named Control, since its descendants are all control elements for windows, and it itself is a descendant of Interactor.

By isolating the common features of all control elements, Control provides some code reuse. In the current design, Control isn't used for polymorphism. However, in a possible alternate design, Win objects could contain a collection of generic Control objects, instead of a fixed number of specific Controls, like two scroll bars. In such a design, Control would provide a useful abstract interface to scroll bars, buttons, and any other interactive elements you define.

The revised hierarchy is shown in Figure 10.7.

You can now define new types of windows, descended from Win, that contain buttons. For example, imagine a class LifeWin that runs the game of Life in a window. This class can inherit the scrolling and cursor movement functionality of TextWin, but it can respond differently to mouse actions on the window, as well as provide commands through buttons. This is illustrated in Figure 10.8.