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