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

发布于 2024-10-08 06:26:29 字数 1165 浏览 2 评论 0原文

我很好奇为什么在 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);
    }
}

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);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白云不回头 2024-10-15 06:26:29

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

bar.setOpaque(true);

You can try making the layered pane opaque:

bar.setOpaque(true);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文