Michele Da Ros
Michele Da Ros

Reputation: 906

how can I create a graphics object in java?

Hi I'm trying to generate an image with java

int width = 640; int height= 480;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g2 =  image.getGraphics();
    g2.setColor(Color.BLUE);
    g2.clearRect(0, 0, width, height);
    ImageIO.write(image, "PNG", new File(path+index+".png"));

I'm expecting a blue image... but it's black. Do you know why?

Upvotes: 0

Views: 896

Answers (2)

Peter Walser
Peter Walser

Reputation: 15706

Graphics::clearRect() does not use the current Color (or rather: Paint).

Javadoc:

Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.

Solution: use fillRect() instead.

Upvotes: 1

Jesper
Jesper

Reputation: 206956

It's black instead of blue because clearRect fills the rectangle with the background color, which is not the color that you set with setColor.

The API documentation of clearRect says:

Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.

Beginning with Java 1.1, the background color of offscreen images may be system dependent. Applications should use setColor followed by fillRect to ensure that an offscreen image is cleared to a specific color.

So, use fillRect instead of clearRect.

g2.setColor(Color.BLUE);
g2.fillRect(0, 0, width, height);

Upvotes: 4

Related Questions