Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

java - Drawing a background image

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.

The picture drawing looks like that:

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

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: enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

enter image description here

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...