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 中的背景图像


基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01