【问题标题】:How to set a background color on a JLayeredPane?如何在 JLayeredPane 上设置背景颜色?
【发布时间】:2011-05-27 16:23:27
【问题描述】:

我很好奇为什么在 JLayeredPane 上调用 setBackground(Color) 似乎并没有真正设置背景颜色。我猜这与 JLayeredPane 出于某种原因必须具有透明背景有关吗?无论如何,这里有一些显示问题的代码。这是在 Mac 上,所以我相信它使用的是 OSX LAF。这产生的结果由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);
    }
}

【问题讨论】:

    标签: java swing background transparency jlayeredpane


    【解决方案1】:

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

    bar.setOpaque(true);
    

    【讨论】:

    • 知道为什么默认设置为 false 吗?
    • 不确定,Swing 教程将分层窗格描述为“为定位提供第三维度的 Swing 容器”。所以我不知道为什么它与做二维定位的 JPanel 有什么不同。
    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 2013-07-21
    • 1970-01-01
    • 2020-01-25
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    相关资源
    最近更新 更多