3

I'm curious why calling setBackground(Color) on a JLayeredPane doesn't seem to actually set a background color. I would guess it has something to do with the JLayeredPane having to have a transparent background for some reason? Anyways, here is some code that shows the issue. This is on Mac, so I believe it's using the OSX LAF. The result this produces is shown by this image.

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {

        // This should be done with Swing Utilities, but I wanted to keep this
        // simple...
        JFrame foo = new JFrame();
        foo.setSize(new Dimension(500, 500));

        JLayeredPane bar = new JLayeredPane();
        bar.setPreferredSize(new Dimension(200, 200));
        bar.setBackground(Color.red);

        // If you comment out the following line, you don't see any indication
        // the JLayeredPane is actually being drawn to screen
        bar.setBorder(BorderFactory.createLineBorder(Color.green));


        JPanel content = new JPanel();
        content.add(bar);

        foo.setContentPane(content);
        foo.setVisible(true);
    }
}
Codemwnci
  • 54,176
  • 10
  • 96
  • 129
Hamy
  • 20,662
  • 15
  • 74
  • 102

1 Answers1

9

You can try making the layered pane opaque:

bar.setOpaque(true);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Any idea why it's set as false by default? – Hamy Dec 18 '10 at 22:21
  • Not sure, the Swing tutorial describes a layered pane as "a Swing container that provides a third dimension for positioning". So I'm not sure why it would be any different than a JPanel which does two dimensional positioning. – camickr Dec 18 '10 at 22:32