title: How to make a lightweight Swing or AWT component translucent in Java
body: <p>A while ago, I tried to implement a semitransparency method for Swing/AWT components, and just now tried it out for the first time. However, several glitches in the UI surface upon implementation. The code of the method is below:</p>
  
  <pre><code>  public static void setTransparency(Component comp, float t)
    {
      try
      {
        if (comp instanceof Window)
        {
          try
          {
  //For JDK 1.7
            ((Window) comp).setOpacity(t);
          }
          catch (Throwable th)
          {
            System.err.println("JRE may be less than 1.7!");
            if (!th.getClass().isInstance(new NoSuchMethodError()))
              th.printStackTrace();
            try
            {
  //For JDK 1.6
              com.sun.awt.AWTUtilities.setWindowOpacity((Window) comp, t);
            }
            catch (Throwable th1)
            {
              throw new UnsupportedOperationException("It seems that transparency is not supported", th1);
            }
          }
        }
        else
        {
          if (comp instanceof JComponent)
            ((JComponent)comp).setOpaque(false);
          Graphics2D g2 = (Graphics2D) comp.getGraphics().create();
          g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, t));
          comp.paint(g2);
          g2.dispose();
        }
      }
      catch (Throwable th)
      {
        throw new UnsupportedOperationException("Transparency might not be supported", th);
      }
    }
  </code></pre>
  
  <p>When run, the component does not change in appearance. <strong>Does anyone have a suggestion for making a Swing or AWT component semitransparent that is 100% reliable?</strong> This only applies to lightweight components, as heavyweight transparency is separately covered and 100% reliable, as shown above.</p>