The TexturePaint class can be used to achieve that.
public void paintComponent(Graphics g)
{
if(paint == null)
{
try
{
// Create TexturePaint instance the first time
int height = image.getHeight(this);
int width = image.getWidth(this);
bi = (BufferedImage) createImage(width, height);
Graphics2D biG2d = (Graphics2D) bi.getGraphics();
biG2d.drawImage(image, 0, 0, Color.black, this);
paint = new TexturePaint(bi,
new Rectangle(0,0,width,height));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
// Now actually do the painting
Graphics2D g2d = (Graphics2D) g;
if(paint != null)
{
g2d.setPaint(paint);
g2d.fill(g2d.getClip());
}
}
written by objects
\\ tags: image, JPanel, panel, TexturePaint, tiled
You can create a JPanel subclass that uses the size of the panel to determine what size to paint the image. The image can then be painted in the (overridden) paintComponent() method at the required size.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ScaledImagePanel extends JPanel
{
private Image imageToDisplay = null;
public void setImageToDisplay(Image imageToDisplay)
{
this.imageToDisplay = imageToDisplay;
}
@Override
protected void paintComponent(Graphics g)
{
Dimension size = getSize();
if (imageToDisplay!=null && size.width>0)
{
g.drawImage(imageToDisplay,
0, 0, size.width, size.height,
0, 0, imageToDisplay.getWidth(null),
imageToDisplay.getHeight(null),
null);
}
}
}
written by objects
\\ tags: image, panel