如何在 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);
}
}
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使分层窗格不透明:
You can try making the layered pane opaque: