绘制背景图像 [英] Drawing a background image

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

问题描述

我绘制的图像是我的背景图像,一切都很好但是当我试图在框架中添加一些JButton时,整个业务出错了我绘制的图片消失了,我看到原始背景。

I draw an image which is my background image, everything is fine but when I'm trying to add some JButtons to the frame the whole business goes wrong the picture that I drew disappear and I see the original background.

图片显示如下:

public void paint(Graphics g){
    g.drawImage(bg, 0, 0, null);
}

我想我的问题与paint方法有关,需要提一下我正在扩展JFrame类。

I guess my problem is something with the paint method, need to be mentioned that I'm extending the JFrame class.

编辑:
这里有一些图片来证明我的意思。

edit: Here are some pictures to demonstrate what I mean.

首先绘制我的图像:

It first draw my image:

当我将鼠标移动到我的按钮应该绘制的位置时,这就是我得到的:

And when I move my mouse to the place that my buttons should have been drew, that's what I get:

推荐答案

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;

public class FrameWithBG {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://i.stack.imgur.com/OVOg3.jpg");
        final BufferedImage bg = ImageIO.read(url);
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JPanel c = new PanelWithBackgroundImage(bg);
                c.setLayout(new GridLayout(0,5,16,16));
                c.setBorder(new EmptyBorder(10, 10, 10, 10));
                for (int ii = 1; ii < 26; ii++) {
                    c.add(new JButton("Button " + ii));
                }
                JFrame f = new JFrame(c.getClass().getSimpleName());

                f.add(c);
                f.pack();
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}

class PanelWithBackgroundImage extends JPanel {

    Image bg;

    PanelWithBackgroundImage(Image bg) {
        this.bg = bg;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
    }
}

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

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