How to set a background color on a JLayeredPane?
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 indicatio开发者_C百科n
// 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);
}
}
You can try making the layered pane opaque:
bar.setOpaque(true);
精彩评论