JLayer component

The JLayer class is a flexible and powerful decorator for Swing components, which enables you to implement various advanced painting effects as well as receive notifications of all AWTEvents generated within its borders. It enables you to draw on components and respond to component events without modifying the underlying component directly.

JLayer is a good solution if you only need to do custom painting over compound component or catch input events from its subcomponents.

Software Requirement: Java Platform SE 7 (jdk1.7)

Here is a sample example,


class WallpaperLayerUI extends LayerUI<JComponent> {
  public void paint(Graphics g, JComponent c) {
    super.paint(g, c);

    Graphics2D g2 = (Graphics2D) g.create();

    int w = c.getWidth();
    int h = c.getHeight();
            AlphaComposite.SRC_OVER, .5f));
    g2.setPaint(new GradientPaint(0, 0, Color.yellow, 0, h, Color.red));
    g2.fillRect(0, 0, w, h);

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Wallpaper {
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
  public static void createUI() {
    JFrame f = new JFrame("Wallpaper");
    JPanel panel = createPanel();
    LayerUI<JComponent> layerUI = new WallpaperLayerUI();
    JLayer<JComponent> jlayer = new JLayer<JComponent>(panel, layerUI);
    f.add (jlayer);
    f.setSize(300, 200);
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo (null);
    f.setVisible (true);
  private static JPanel createPanel() {
    JPanel p = new JPanel();
    ButtonGroup entreeGroup = new ButtonGroup();
    JRadioButton radioButton;
    p.add(radioButton = new JRadioButton("Beef", true));
    p.add(radioButton = new JRadioButton("Chicken"));
    p.add(radioButton = new JRadioButton("Vegetable"));
    p.add(new JCheckBox("Ketchup"));
    p.add(new JCheckBox("Mustard"));
    p.add(new JCheckBox("Pickles"));
    p.add(new JLabel("Special requests:"));
    p.add(new JTextField(20));
    JButton orderButton = new JButton("Place Order");
    return p;
The output  will be like below:

A panel with a jazzy decoration

Permanent link to this article: https://blog.openshell.in/2011/04/jlayer-component/

Leave a Reply

Your email address will not be published.