Background Image on a Component
How do I add a background image to a component, in this case, a scrollpane containing a drawing area. This is for a level editor for my game. I want a level's background image to be drawn and tiled so the user can get a better preview of what the level will really look like. Is there an easy way to do this?
[323 byte] By [
Eliwood] at [2007-9-30 7:04:02]

Override paintComponent(Graphics) from JComponent and draw your image using the Graphics class.
e.g.
public void paintComponent(Graphics g){
g.drawImage(yourImage, 0,0, this);
}
Tiling images can be done with the TexturePaint class.
Do you have a little code-snippet on how to use this class? The only things I've ever needed to do in graphics is loading, transforming, and drawing images, so I'm a bit in the dark on anything outside that.
> Do you have a little code-snippet on how to use this
> class? The only things I've ever needed to do in
> graphics is loading, transforming, and drawing images,
> so I'm a bit in the dark on anything outside that.
I think something like this will do it. I don't know for sure though since I've never used it:
private BufferedImage bImage;
// ... constructors, code blahdy blah, construct the bufferedimage here etc.
public void paintComponent(Graphics g) {
// the Rectangle2D in user space used to anchor and replicate the texture:
Rectangle2D anchor = new Rectangle2D.Double(0,0,20,20);
// the actual paint object:
TexturePaint tpaint = new TexturePaint(bImage, anchor);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(tpaint);
// g2d.fillRect(0,0,getWidth(), getHeight());
}
You shouldn't realy create TexturePaint objects on the fly, especially if you are using alot of them (the TexturePaint class takes a *copy* of the supplied BufferedImage).
TexturePaint realy is too inefficient to be of much use to most people, especially when you can perform the same task yourself using clip(Shape) and drawImage(). (and in your case, you don't even need the clip() )
Abuse at 2007-7-1 23:05:15 >
