Select Button Group
Posted by Darryl Burke on November 9, 2008
Anyone using ButonGroup for the first time has scoured the API for a method that returns the selected Button. Alas, getSelection() returns a ButtonModel, not a button. And as the MVC pattern of Swing allows a visual component – a View – to share its Model with other visual components, ButtonModel rather obviously doesn’t provide a method to get the button from its model.
SelectButtonGroup attempts to address the shortcomings of ButtonGroup by providing additional methods that shorten user code and make programs using the class easy to write and maintain. The class also offers property change support on the same lines as visual components.
The class provides new methods to get and set the selected button and index. The getSelectedIndex() method can be particularly useful in conjunction with a PropertyChangeListener, facilitating a switch-case construct for processing user selection. A setEnabled(boolean) method facilitates simultaneously enabling or disabling all the buttons of the group. This does not obviate the option of setting the enabled property of any individual button, so a corresponding getEnabled() would be meaningless and was not provided.
A potential problem in ButtonGroup is that it allows the same button to be added more than once, and removal from the group will only negate the first of such additions. Moreover, adding a button that already belongs to one group to a different group succeeds, while not removing the button from its earlier group’s population. While this may not have immediate effect on GUI interaction, it does mean that the value returned by getButtonCount() is unreliable. SelectButtonGroup will not allow a repeat addition of the same button to the same or any other SelectButtonGroup and will also prevent addition of any button that has a DefaultButtonModel or other model that provides a getGroup() method, if it is already a member of any ButtonGroup.
In a large application, it is recommended to invoke dispose() on a SelectButtonGroup that is no longer needed. This releases static references to the buttons contained in the group and makes them eligible for garbage collection.