在JFrame中的背景图像 [英] Background image in a JFrame

查看:106
本文介绍了在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); 时,背景显示但不是我的其他组件。我猜这与paintComponent没有被null LayoutManager调用有关,但我对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).

当我制作图像时,背景必须显示为null(因此,透明(??)),红色方块显示出来,因此背景可能是实际上高于我的其他组件。

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中的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆