给面板添加背景图片

给JPanel添加背景图片:

代码入下:

 1 package test;
 2 
 3 import java.awt.Graphics;
 4 import java.awt.Image;
 5 
 6 import javax.swing.ImageIcon;
 7 import javax.swing.JPanel;
 8 
 9 public class BackgroundPanel extends JPanel {
10     private int width;
11     private int height;
12     private Image img;
13     
14     public BackgroundPanel(String imgPath, int width, int height) {
15         this(new ImageIcon(imgPath).getImage(), width, height);
16     }
17     
18     public BackgroundPanel(Image img, int width, int height) {
19         this.width = width;
20         this.height = height;
21         this.img = img;
22     }
23     
24     public void paint(Graphics g) {
25         g.drawImage(img, 0, 0, width, height, null);
26     }
27     
28 }
View Code

测试代码:

 

 1 package test;
 2 
 3 import javax.swing.JFrame;
 4 import javax.swing.JPanel;
 5 
 6 public class Test {
 7     public static void main(String[] args) {
 8         final int WIDTH = 600;
 9         final int HEIGHT = 600;
10         JFrame frame = new JFrame("测试背景面板");
11         JPanel panel = new BackgroundPanel("imgPath", WIDTH, HEIGHT);
12         frame.add(panel);
13         frame.setSize(WIDTH, HEIGHT);
14         frame.setVisible(true);
15         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16     }
17 }
View Code

 

 

 

posted @ 2014-04-17 20:03  瓦尔登湖畔的小木屋  阅读(411)  评论(0编辑  收藏  举报