图像和面板 [英] Images and Panels

查看:99
本文介绍了图像和面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在在Image顶部添加JPanel时遇到问题.这就是我想要做的:

I'm having a problem adding a JPanel on top of an Image. This is what I'm trying to do:

Image bgImage = loadImage(filename);
JPanel jp = new JPanel();

jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);

bgImage.add(jp);

这样做之后,我只会看到bgImage.我尝试了所有操作,但仍然无法显示面板.有人可以帮我吗?

After doing this, I only see the bgImage. I tried everything but I still can't show the panel. Can somebody help me?

推荐答案

您不能将组件放置在Image内.您要做的是将Image绘制到摆动组件的背景上(例如JPanel).所有的swing组件都有一个paint()方法,该方法调用以下三个方法(可能不是此顺序):paintComponent()paintChildren()paintBorder().因此,您想覆盖paintComponent()方法以在面板上绘制背景图像.运行此命令时,将调用您的自定义方法,然后将调用paintChildren()方法,该方法将在背景图像的顶部绘制所有子"组件:

You cannot place a component inside an Image. What you want to do is paint the Image onto the background of a swing component (like JPanel). All swing components have a paint() method that calls these three methods (perhaps not quite this order): paintComponent(), paintChildren(), paintBorder(). So, you want to override the paintComponent() method to paint your background image over the panel. When this runs, your custom method will be called, and then the paintChildren() method will be called, which will paint all "child" components over the top of your background image:

class BackgroundImagePanel extends JPanel {

    public void setBackgroundImage(Image backgroundImage) {
        this.backgroundImage = backgroundImage;
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        graphics.drawImage(backgroundImage, 0, 0, this);
    }

    private Image backgroundImage;
}

BackgroundImagePanel panel = new BackgroundImagePanel();
panel.setBackgroundImage(image);
panel.add(new JTextField("Enter text here..."));
panel.add(new JButton("Press Me"));

这篇关于图像和面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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