Java Tips Weblog

  • Blog Stats

    • 1,518,025 hits
  • Categories

  • Archives

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.

Get The Code

See Also

Dual Icon

Related Reading

The Java™ Tutorials: How to Use Icons
Java API: javax.swing.Icon

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 103 other followers

%d bloggers like this: