Example of transparent windows with Swing, AWT and Java2D in Java

Java: Transparent Windows Using Swing, AWT and Java2D (Part 1)

Summary:

In the field of optics, the distinction between transparency and translucency is of great importance. However, the exact differences only become clear on a macroscopic scale. Fortunately, the world of software development is much simpler than the world of physics.

Preface

In the field of optics, the distinction between transparency and translucency is of great importance. However, the exact differences only become clear on a macroscopic scale. Fortunately, the world of software development is much simpler than the world of physics. For this reason we use simplified definitions of these terms throughout this series of articles. Nevertheless, we try to use the terms as accurately as possible.

Terminology and Examples

In programming, the terms transparency and translucency are often used interchangeably. ‘Translucency‘ is sometimes also used to describe a glass effect where an image, or parts of it, are blurred out.

Transparent window example in Java with Swing
Fully transparent window

Transparency
A transparent material permits light to pass through without being scattered. Transparent materials appear so clear you can see through them as if there is nothing there. They appear absolutely invisible. If a material is transparent it has an opacity of 0.

Translucency
A translucent material permits some light to pass through. The material scatters the light which results in diffusion or distortion. To achieve this effect, the pixels of the layers are usually composed together in a back-to-front order using an (alpha) blending equation.

Example of a translucent window in Java with Swing
Translucent window with an opacity of 45%
(55% translucency)
Example of a fully opaque window
Fully opaque window

Opacity
A material is opaque if it absorbs all (visible) light. A fully opaque surface permits no light to pass through. However, the material itself emits some light.

  • Opacity is the opposite of transparency.
  • If a material has a high trans-lucency, it has a low opacity.

Blending operates on single pixels. Compositing operates on images.

Source Code – Simple Translucent Window in Java

/**
 * The TranslucentWindowMin program implements a min. application which
 * makes a window translucent using uniform translucency.
 *
 * @author  nullraum.net
 */

import java.awt.*;
import javax.swing.*;

public class TranslucentWindowMin extends JFrame
{
    public TranslucentWindowMin() {

        setTitle("Translucent Window Example");

        setSize(300,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        // Set the window to 45% opaque = 55% translucent
        setOpacity(0.45f);
    }
    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TranslucentWindowMin().setVisible(true);
            }
        });
    }
}

Source Code – Simple Transparent Window in Java

/**
 * The TransparentWindowMin program implements a min. application which
 * makes a window fully transparent using simple uniform translucency.
 *
 * @author  nullraum.net
 */

import java.awt.*;
import javax.swing.*;

public class TransparentWindowMin extends JFrame
{
    public TransparentWindowMin() {

        setTitle("Transparent Window Example");

        setSize(300,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        // Set the window to 0% opaque = transparent
        setOpacity(0.0f);
    }
    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TransparentWindowMin().setVisible(true);
            }
        });
    }
}

Binary Transparency and Alpha Transparency

There are two different approaches for supporting transparent images areas in raster file formats: simple binary transparency and alpha transparency.

With binary transparency one or more colors of the indexed color palette are explicitly defined as transparent (GIF format). A pixel is either visible or not. No intermediate opacities are possible which, among other things, leads to ‘harder’ edges.

With alpha transparency the transparency information is stored in a separate channel which means that the opacity levels can be controlled on a per pixel basis (PNG format). Therefore, this approach supports gradations of opacity which allows ‘softer’ edges and smoother transitions.

Example of binary transparency (GIF)
Binary transparency leads to ‘hard’ edges (GIF)
Example of alpha transparency (PNG)
Alpha transparency leads to smoother transitions (PNG)

Examples of raster file formats that support transparency in one way or the other are PNG, GIF, BMP, TIFF, and JPEG 2000. Regular JPEG files (ISO/IEC 10918) don’t support transparency.

Color Depths and Channels of Bitmaps / Video Framebuffers

True color (24-bit) Bitmaps almost always use 8 bits for each of the 3 channels red, green and blue per pixel (RGB color model). This allows 28 (256) different luminosity levels per channel. As a result, such bitmaps allow 224 (16,777,216) color combinations.

Bitmaps with a depth of 32 bits also consist of three channels with 8 bits each (R=red, G=green, B=blue) but have an additional 4th channel (A=alpha) which is normally used for modelling opacity.

Red, green, blue, alpha (RGBA) is basically an extension of the RGB color model with an extra channel containing information about opacity. Usually the alpha channel has the same color depth as the other channels (8 bits).

We need 32 bits per pixel to represent a color bitmap with an alpha channel (8 bits for red + 8 bits for green + 8 bits blue + 8 bits for alpha).

Representation of a single pixel in memory

Layout in memory of the four channels: Alpha, Blue, Green, Red showing ABGR8888 encoding.
Representation of a pixel using ABGR8888 encoding scheme (Byte-order, Little-endian).

Pixel values and ranges

The pixel values are usually represented as unsigned integers ranging from 0 to 255 where an alpha value of 0 stands for (total) transparency and an alpha value of 255 stands for (full) opacity. 32-bit bitmaps support 232 (4,294,967,296) color combinations.

RGBA pixel values of a translucent PNG.
RGBA values of a translucent pixel
(Software Gimp: Hold <SHIFT> while using the color picker to show this window)

Example: CSS rgba() Function

The rgba() function in CSS define colors using the above mentioned Red-green-blue-alpha (RGBA) model.
The alpha parameter is a floating point number between 0.0 (fully) transparent and 1.0 (fully) opaque. The background pixels (unicorn) and the corresponding translucent foreground pixels are blended together.

Violet:  rgba(148, 0, 211, 0.5)

Indigo: rgba(75, 0, 130, 0.5)

Blue:    rgba(0, 0, 255, 0.5)

Green:  rgba(0, 255, 0, 0.5)

Yellow:   rgba(255, 255, 0, 0.5)

Orange: rgba(255, 127, 0, 0.5)

Red:       rgba(255, 0, 0, 0.5)

In addition to RGB and RGBA, other color models such as HSL (Hue, Saturation and Lightness) or HSLA (HSL with an alpha channel extension) are available in CSS. Read the article about colors and stand alone opacity on w3schools if you want to learn more about color models in CSS.

Alpha Blending in 2D Computer Graphics

Alpha blending has uses in many fields and refers to many different operations. For us, it is the process of combining a background color with a translucent foreground color, thereby producing a new blended color.[1]

Alpha blending operates on single pixels. If we work with RGBA pixels, usually the alpha values of both, the source pixel and the destination pixel, are taken into account when calculating the new color components. However, which algorithm is used for alpha blending and how exactly the results should look like, depend on the specific application.

Alpha Blending Basics

We assume that we compose all fragments in back-to-front order, that we work with RGBA pixels and that the possible value of alpha ranges from 0.0f to 1.0f, inclusive. Let’s think about some possible cases.

Painted in back-to-front order. Green is the background color. Red is the foreground color. In case 1, the gray color indicates complete transparency of the foreground rectangle.

Alpha blending with transparent foreground color
Case 1: Alpha=0.0f
Foreground color is completely transparent. Background color get’s drawn.
Alpha blending with opaque foreground color
Case 2: Alpha=1.0f
Foreground color is completely opaque. Foreground color get’s drawn.
Alpha blending with translucent foreground color and translucent background color
Case 3: Alpha lies in between 0.0f and 0.1f
Foreground and background pixels must be blended

Normal cases
Case 1: If the foreground color is transparent (alpha=0.0f), the new color will be the background color (including it’s alpha).
Case 2: If the foreground color is completely opaque (alpha=1.0f), the new color will be the foreground color and alpha will be 1.0f.
Case 3: If alpha lies in between these values (0.0f, 1.0f), an equation for calculating the color components (including alpha) is needed.

Edge cases
If both, the foreground pixel and the background pixel are transparent, the new pixel will also be transparent.
If the foreground pixel and the background pixel are completely opaque, the new color will be the foreground color and it’s alpha will be 1.0f.

Alpha Blending using the Over Operator

In 2D computer graphics the most commonly used operator for alpha blending and for simulating translucency is probably the over operator. It works on RGBA pixels with and without premultiplied alpha.

The over operator is one of 12 operators which were described by Porter and Duff in their paper Compositing Digital Images (1982). However, the operator was not intended to be used for blending pixels but to overlay and combine images. Alpha blending is only one application of the over operator.

Image compositing. Over, in, atop, xor operator
Image from: Wikipedia.org

Alpha Blending

Normal RGBA Pixel
Pixel(x|y) = (R, G, B, α)

RGBA Pixel with premulit. α
Pixel(x|y) = (α*R, α*G, α*B, α)

Translucency in Java

Java Swing supports both uniform translucency and per-pixel translucency. While uniform translucency is simple to implement by invoking window’s setOpacity(float opacity) method, per-pixel translucency requires a few more mandatory steps like defining alpha values over the rectangular window area by invoking window’s setBackground(Color bgColor) method.

Uniform Translucency in Java

In Java a window with uniform translucency can be created by invoking the window’s setOpacity(float opacity) method. Each pixel of this window will be drawn with the same alpha value. The parameter of this function takes a floating point value in the range of 0.0f (fully transparent) to 1.0f (fully opaque).

Window with simple uniform translucency created in Java Swing

Java uniform translucency example
PNG image (with transparency) drawn on an uniform translucent window created by window’s setOpacity() method with an opacity of 45%.

Each pixel is drawn with the defined opacity of 45% (55% translucency).

Uniform translucency in Java is easy to implement, fast and uses less memory than per-pixel translucency. The downside is that gradations of opacity or alpha compositing are not possible. Each pixel of the surface has the same translucency.

If you want to use uniform translucency be sure not to invoke window’s setBackground(Color bgColor) method with an alpha < 255 because this installs per-pixel translucency. Read more about that.

Per-Pixel Translucency in Java

Per-pixel translucency in Java with a gradient
Per-pixel translucency in Java with a gradient

Java per-pixel translucency example
PNG image (with transparency) drawn on a JPanel with a gradient and decreasing translucency.

The tranclucency is decreasing while the gradient moves toward the bottom of the window.

In Java per-pixel translucency requires a few initial steps like defining alpha values over the rectangular window area by invoking window’s setBackground(Color bgColor) method, but in general, it is also easy to implement.

With per-pixel translucency it is possible to create gradients with different alpha levels and to use alpha compositing. It uses more memory and is not as fast as uniform translucency. But that doesn’t usually matter in 2D computer graphics when painting windows for desktop applications.

The final color of the pixel also depends on the alpha value that may have been previously passed to the setOpacity(float opacity) method. If an alpha value below 1.0f was passed to this method, the foreground pixels (component, control, brush,…) and background pixels (window) are alpha blendend using the over operator. The blending behavior can be changed using Java’s AlphaComposite class.

References

https://en.wikipedia.org/wiki/Color_depth
https://x-equals.com/taking-a-byte-out-of-bit-depth-jpeg-vs-raw/
https://www.w3schools.com/css/css3_colors.asp
https://parnassus.co/transparent-graphics-with-pure-gdi-part-1/ https://developer.nvidia.com/content/transparency-or-translucency-rendering
http://streaming.discoveryeducation.com/braingames/Optics/OR/DiscoverMore/Opaque.htm
https://www.slideshare.net/Mark_Kilgard/08blend
http://www.idux.com/2011/02/27/what-are-index-and-alpha-transparency/
https://docs.gimp.org/2.8/en/gimp-using-web-transparency.html
https://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html
https://www.informit.com/articles/article.aspx?p=1592963&seqNum=2
https://keithp.com/~keithp/porterduff/p253-porter.pdf

Pascal Werkl
Written by
Pascal Werkl
Join the discussion

Pascal Werkl

Pascal Werkl

Pascal is a computer scientist/software engineer and digital marketer by profession with over 15 years of experience in the industry. He is skilled in data science, statistical data exploration and data visualization.

At the moment, he is trying to exhaust the limits of augmented reality in marketing using Google's ARCore and Unity's 3D Engine.