Ecco un esempio completo che mostra un panel in cui l'immagine viene "ripetuta" su tutta la superficie.
codice:
import java.awt.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class TestFrame extends JFrame
{
public TestFrame (Image img)
{
super ("Test Background Panel");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize (300, 300);
JPanel panel = new BackgroundPanel (img);
add (panel);
}
public static void main (String[] args)
{
try
{
URL imageUrl = new URL ("http://img502.imageshack.us/img502/4725/grey036qf9.jpg");
final Image img = ImageIO.read (imageUrl);
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
TestFrame f = new TestFrame (img);
f.setVisible (true);
}
});
}
catch (Exception e)
{
System.out.println (e);
}
}
}
class BackgroundPanel extends JPanel
{
private Image img;
public BackgroundPanel (Image img)
{
this.img = img;
}
public void paintComponent (Graphics g)
{
Dimension panelSize = getSize ();
int width = img.getWidth (this);
int height = img.getHeight (this);
for (int y = 0; y < panelSize.height; y += height)
{
for (int x = 0; x < panelSize.width; x += width)
{
g.drawImage (img, x, y, this);
}
}
}
}
P.S.: nell'esempio ho caricato l'immagine da un URL ma ovviamente si può anche caricare da altre sorgenti, es. da un file.