ButtonGroup - Final Version
Button Group - Radio Group Logic
In the previous section, we discussed how to create a group of buttons which behave like radio buttons. In our ButtonGroup class, we created 3 instances of Button objects, then we defined methods which explicitly called each method for the button object instances. This is fine for our first pass at creating the Menu class, but once we figured out the required logic for implementing the button behavior, now we need to step back and analyze the code to see if we can make improvements. We can observe that the main function of the Menu class is to implement the Finite State Machine logic to control the activation of the group of Buttons: only 1 button can be active at any time, we need a state variable to remember which button is the currently active button.
Observations:
Arrays as Constructor Input Parameters
For maximum flexibility for collections of objects like our ButtonGroup that is composed of Buttons, one powerful approach is that we can declare an Array of Buttons as an instance variable for the class, then we can have an Array of Buttons as an input parameter for the ButtonGroup Constructor. This allows us to provide more specific configuration details for each button before adding it to the ButtonGroup.
When we pass an object into any function, what we are actually doing is passing the reference, or memory address, of that object into the function. Since a constructor is a special type of function, objects passed to constructors are also passed by reference. This is extremely helpful for us. See the section on Object Reference Data Types for more detail on this.
Initialize Button Array in Main Tab
Below is the code in the program's main tab to initialize the buttons
array.
If we look at the code for our initial attempt at writing the ButtonGroup class, can discover patterns that can help us now that we're trying to modify our code to use an Array of Button objects in our Menu Class.
ButtonGroup clicked(int mx, int my)
Below is the array version of the above code. See comments to indicate that additional code was added to implement the specified functionality.
Last updated