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

3

我很好奇在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);
    }
}
1个回答

9
您可以尝试使分层面板不透明:
bar.setOpaque(true);

默认为什么设置为false? - Hamy
不确定,Swing教程将分层面板描述为“提供第三维定位的Swing容器”。因此,我不确定它与执行二维定位的JPanel有何不同。 - camickr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接