Background image in a JFrame(JFrame 中的背景图像)
问题描述
这个问题被问了很多,但到处都没有答案.通过扩展 JPanel 并覆盖paintComponent,我可以让 JFrame 很好地显示背景图像,如下所示:
This question has been asked a lot but everywhere the answers fall short. I can get a JFrame to display a background image just fine by extending JPanel and overriding paintComponent, like so:
class BackgroundPanel extends JPanel {
private ImageIcon imageIcon;
public BackgroundPanel() {
this.imageIcon = Icons.getIcon("foo");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageIcon.getImage(), 0,0,imageIcon.getIconWidth(),imageIcon.getIconHeight(),this);
}
}
但是现在,如何在该背景之上添加一个组件?我去的时候
But now, how do you add a component on top of that background? When I go
JFrame w = new JFrame() ;
Container cp = w.getContentPane();
cp.setLayout(null);
BackgroundPanel bg = new BackgroundPanel();
cp.add(bg);
JPanel b = new JPanel();
b.setSize(new Dimension(30, 40));
b.setBackground(Color.red);
cp.add(b);
w.pack()
w.setVisible(true)
它显示红色小方块(或任何其他组件)而不是背景,但是当我删除 cp.setLayout(null);
时,背景会显示但我的其他组件不显示.我猜这与 null LayoutManager 未调用paintComponent 有关,但我一点也不熟悉 LayoutManagers 的工作原理(这是一个大学项目,作业特别说明不要使用 LayoutManager).
It shows the little red square (or any other component) and not the background, but when I remove cp.setLayout(null);
, the background shows up but not my other component. I'm guessing this has something to do with the paintComponent not being called by the null LayoutManager, but I'm not at all familiar with how LayoutManagers work (this is a project for college and the assignment specifically says not to use a LayoutManager).
当我制作图像时,背景必须显示为空(因此,透明 (??)),红色方块会显示出来,因此可能是背景实际上位于我的其他组件之上.
When i make the image the background has to display null (and so, transparant (??)) the red square shows up so it might be that the background is actually above my other components.
有人有什么想法吗?
谢谢
推荐答案
当使用 null
布局时(你几乎从不应该)你必须为每个组件,否则默认为 (0 x,0 y,0 width,0 height) 组件不会显示.
When using null
layout (and you almost never should) you have to supply a bounds for every component, otherwise it defaults to (0 x,0 y,0 width,0 height) and the component won't display.
BackgroundPanel bg = new BackgroundPanel();
cp.add(bg);
没有提供界限.您需要执行以下操作:
isn't supplying a bounds. You'll need to do something like:
BackgroundPanel bg = new BackgroundPanel();
bg.setBounds(100, 100, 100, 100);
cp.add(bg);
这将使 bg
大小为 100 x 100 并将其放置在框架上 100 x、100 y 处.
Which would make bg
size 100 x 100 and place it at 100 x, 100 y on the frame.
这篇关于JFrame 中的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JFrame 中的背景图像


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01