如何在JLayeredPane上设置背景颜色?

Ham*_*amy 2 java swing transparency background jlayeredpane

我很好奇为什么在JLayeredPane上调用setBackground(Color)似乎并没有真正设置背景颜色.我猜它与JLayeredPane有某种关系因为某些原因必须有透明背景?无论如何,这里有一些显示问题的代码.这是在Mac上,所以我相信它正在使用OSX LAF.此图像显示了结果.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 7

您可以尝试使分层窗格不透明:

bar.setOpaque(true);
Run Code Online (Sandbox Code Playgroud)