Toggle Button Icons
Posted by Darryl Burke on March 25, 2009
Discovering the hard way that the part of a JCheckBox or a JRadioButton that indicates its selected or rollover status is in fact the default icon of the component, and that invoking setIcon replaces the default icon with your custom icon, can be disconcerting or even exasperating.
CheckBoxIcon and RadioButtonIcon, which inherit from DualIcon, published earlier, through an abstract class ToggleButtonIcon, allow you to add a custom icon to these Swing components alongside the functional one.
These classes are each furnished with two constructors, one of which computes the relative positioning of the default and custom icon from the icon text alignments of the JCheckBox / JRadioButton, while the other allows the user to specify the horizontal and vertical positions. To add a custom icon to a JCheckBox / JRadioButton with the default alignments, use
checkBox.setIcon(new CheckBoxIcon(checkBox, customIcon));
radioButton.setIcon(new RadioButtonIcon(radioButton, customIcon));
These are the default alignments:
The gap between the two icons is obtained from and equal to the icon text gap of the component.