1 import java.awt.*;
2 import javax.swing.*;
3
4 public class Demo extends JFrame
5 {
6 public Demo()
7 {
8 super("Title");
9 NewPanel p = new NewPanel();
10 this.getContentPane().add(p); //将面板添加到JFrame上
11 this.setSize(596,298); //初始窗口的大小
12 this.setLocationRelativeTo(null); //设置窗口居中
13 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14 this.setVisible(true);
15 }
16
17 public static void main(String[] args)
18 {
19 new Demo();
20 }
21
22 class NewPanel extends JPanel
23 {
24 public NewPanel()
25 {
26
27 }
28
29 public void paintComponent(Graphics g)
30 {
31 int x=0,y=0;
32 java.net.URL imgURL=getClass().getResource("test.jpg");
33
34 //test.jpg是测试图片,与Demo.java放在同一目录下
35 ImageIcon icon=new ImageIcon(imgURL);
36 g.drawImage(icon.getImage(),x,y,getSize().width,getSize().height,this);
37 while(true)
38 {
39 g.drawImage(icon.getImage(),x,y,this);
40 if(x>getSize().width && y>getSize().height)break;
41 //这段代码是为了保证在窗口大于图片时,图片仍能覆盖整个窗口
42 if(x>getSize().width)
43 {
44 x=0;
45 y+=icon.getIconHeight();
46 }
47 else
48 x+=icon.getIconWidth();
49 }
50 }
51 }
52
53 }
54
55
56

 

 

 SCAU_QUE: 由于遇见一些人出现利用JLabel标签来给面板添加背景,噢,不可以说是背景,仅仅是 添加了一张图片而已。

posted on 2010-06-06 16:47  KuSiuloong  阅读(21081)  评论(2编辑  收藏  举报