The JLayeredPane Class

We have already seen some of the panes (the glass and content panes, for example) accessible through the JRootPane class. Though it doesn’t make much use of it directly, JRootPane introduces a class called JLayeredPane. JLayeredPane is a container that manages its components via layers so that components in the upper layers are painted on top of components in the lower layers. This gives you something that was difficult to get with AWT: complete control over which components are painted on top and which are hidden.
The easiest way to understand how this works is to look at a very simple example.

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

public class SimpleLayers extends JFrame {
	public SimpleLayers() {
		super("LayeredPane Demonstration");
		setSize(200, 150);

		JLayeredPane lp = getLayeredPane();

		// Create three buttons.
		JButton top = new JButton();
		top.setBounds(20, 20, 50, 50);
		JButton middle = new JButton();
		middle.setBounds(40, 40, 50, 50);
		JButton bottom = new JButton();
		bottom.setBounds(60, 60, 50, 50);

		// Place the buttons in different layers.
		lp.add(middle, new Integer(2));
		lp.add(top, new Integer(3));
		lp.add(bottom, new Integer(1));

	public static void main(String[] args) {
		SimpleLayers sl = new SimpleLayers();

You may also like...