Posted by Rob Camick on March 29, 2009
Many Swing components support the usage of Icons. Icons can spice up your application when used effectively. You may be familiar with the old saying, “two heads are better than one“? Well, there may be times when two Icons are better than one.
So how do you add multiple icons to a Component when there is only a simple setIcon(…) method? The answer is to combine multiple icons into one and then add the combined icon to the Component. This is what the CompoundIcon class does, it allows you to combine 2 or more Icons into a single Icon. The CompoundIcon class works like a layout manager in that it lays out each Icon in order along one of the following axes:
- X_AXIS – layed out horizontally
- Y_AXIS – layed out vertically
- Z_AXIS – stacked on top of one another
A few constructor parameters exist that allow you to fine tune the positioning of each Icon:
- gap – used by X_AXIS and Y_AXIS. Specifies the number of pixels between each Icon.
- alignmentX – used by Y_AXIS and Z_AXIS. Controls the Icon alignment when the width of a given Icon is less than the width of the largest Icon. Common values would be LEFT, CENTER, RIGHT although any value between 0.0 and 1.0 can be used.
- alignmentY – used by X_AXIS and Z_AXIS. Controls the Icon alignment when the height of a given Icon is less than the height of the largest Icon. Common values would be TOP, CENTER, BOTTOM although any value between 0.0 and 1.0 can be used.
The image below gives an idea of the different layouts that can be achieved:
The center column shows the default layout for each axis. The code to create the last label (in the bottom/right) would be something like:
CompoundIcon icon = new CompoundIcon( CompoundIcon.Z_AXIS, 0, CompoundIcon.RIGHT, CompoundIcon.BOTTOM, red, blue, green); JLabel label = new JLabel( icon );
CompoundIcon is a general purpose class with no ties to any particular Swing component. For a convenience class that allows you to easily combine the LAF toggle button icons (JCheckBox, JRadioButton) with another Icon, check out Darryl’s Toggle Button Icons.
At first it may not be apparent when and where you would use a CompoundIcon. Hopefully my next few postings will give you a couple of ideas.