import java.awt.*;
import javax.swing.*;
public class Demo extends JFrame
{
public Demo()
{
super("Title");
NewPanel p = new NewPanel();
this.getContentPane().add(p); //将面板添加到JFrame上
this.setSize(596,298); //初始窗口的大小
this.setLocationRelativeTo(null); //设置窗口居中
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args)
{
new Demo();
}
class NewPanel extends JPanel
{
public NewPanel()
{
}
public void paintComponent(Graphics g)
{
int x=0,y=0;
java.net.URL imgURL=getClass().getResource("test.jpg");
//test.jpg是测试图片,与Demo.java放在同一目录下
ImageIcon icon=new ImageIcon(imgURL);
g.drawImage(icon.getImage(),x,y,getSize().width,getSize().height,this);
while(true)
{
g.drawImage(icon.getImage(),x,y,this);
if(x>getSize().width && y>getSize().height)break;
//这段代码是为了保证在窗口大于图片时,图片仍能覆盖整个窗口
if(x>getSize().width)
{
x=0;
y+=icon.getIconHeight();
}
else
x+=icon.getIconWidth();
}
}
}
}