java中如何把图片设置为窗体的背景?

来源:百度知道 编辑:UC知道 时间:2024/05/21 16:29:22

重载JPanel的paint

public class MyPanel extends JPanel
{
protected Image backgroundImage;

/* override the paint method to take into account
your background image */
public void paint (Graphics g)
{
// ease image tag
Image i = this.backgroundImage;
/* get image height/width (can send non-null
ImageObservers if you'd rather... */
int h = i.getHeight(null), w = i.getWidth(null);
/* get background from JPanel to fill clear
pixels in the image */
java.awt.Color c = this.getBackground();
// draw the background image to the Graphics
// again, pass a non-null ImageObserver if you like
g.drawImage(i, h, w, c, null);

/* now that your background is drawn, call the
JPanel default paint method which will paint all
its components (over your newly painted background) */
super.paint(g);
}

}