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


基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01