Java Tips Weblog

  • Blog Stats

    • 2,572,390 hits
  • Categories

  • Archives

Alpha Icons

Posted by Darryl Burke on August 22, 2010

These Alpha Icons wrap any Icon and paint it with the specified transparency. As Swing does not play well with an Icon that is not itself an ImageIcon but requires to show an animated GIF, two implementations are provided: AlphaIcon, which is good for wrapping any Icon, including an ImageIcon with a static image, and AlphaImageIcon which extends ImageIcon and can provide transparency for an ImageIcon that holds an animated image.

Each implementation provides a constructor that takes two parameters: the icon to be wrapped, and the opacity, a float value in the range 0.0F (fully transparent) to 1.0F (fully opaque).

When combined with Rob’s CompoundIcon with a Z_AXIS alignment, AlphaIcon and AlphaImageIcon allow you to overlay one Icon on another with the bottom Icon showing through. Multisort Table Header Cell Renderer showcases the use of AlphaIcons with varying transparency to indicate multiple sort orders in the header of a JTable.

Get The Code

AlphaIcon.java
AlphaImageIcon.java

See Also

Compound Icon
Multisort Table Header Cell Renderer

Related Reading

Java API: javax.swing.Icon
Java API: java.awt.AlphaComposite

6 Responses to “Alpha Icons”

  1. Hi Darryl, it looks like both links point to DualIcon.java instead ;-)

  2. Moiz Bhukhiya said

    Can these classes be used for commercial purpose? Thanks!

    • Like all code published on the blog, these classes are free to use, at your own risk . A link to the blog page in the doc comments or elsewhere would be nice, but is by no means mandatory.

      Darryl

  3. Derli said

    Thanks!! it works Greats Darryl !

    Added the following lines to animate a Fade in my App:

    private Component parent;

    public void setAlpha(float newAlpha)
    {
    alpha = newAlpha;
    parent.repaint();
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
    if (icon instanceof ImageIcon) {
    image = ((ImageIcon) icon).getImage();
    } else {
    image = null;
    }
    this.parent = c; // <– Added!
    g2 = (Graphics2D) g.create();
    g2.setComposite(AlphaComposite.SrcAtop.derive(alpha));
    icon.paintIcon(c, g2, x, y);
    // g2.dispose();

    }

Leave a comment