Search code examples
javaawtscreenshot

Screen shot of container has black background instead of white


I have a small java program with the purpose of taking a screen shot of a specific component with the same program.

Here is an MCVE of it

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

@SuppressWarnings("serial")
public class Screen {

    public static void main(String[] args) {
        Frame frame = new Frame("Screen Test!");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                frame.dispose();
             }
         });

        Container container = new Container() {

            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.setColor(Color.RED);
                g.fillRect(5, 5, 10, 10);
            }
        };

        Dimension dimension = new Dimension(50, 50);
        container.setPreferredSize(dimension);

        frame.add(container);
        frame.pack();
        frame.setVisible(true);

        BufferedImage bufImage = new BufferedImage(dimension.width, dimension.height, BufferedImage.TYPE_INT_RGB);
        container.paint(bufImage.createGraphics());

        File outputfile = new File("image.jpg");
        try {
            ImageIO.write(bufImage, "jpg", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

When the code is run it produces this file.

Black Background

However, I was expected an output file which looked like this.

White Background

Have I done something wrong or missed a step?


Solution

  • I think you could try:

    frame.setBackground(Color.WHITE);
    

    Before adding your container

    Don't forget to import the color

    import java.awt.Color;
    

    I think this is because there is no background defined, and windows fills it automatically with a white color, but there is actually no background color, causing it to be black in the screenshot.

    Edit:

    My bad, you need to add the backgroundColor to the Graphics you use to draw the container to the Image.

    try this:

    Graphics2D graphs = bufImage.createGraphics();
    graphs.setBackground(Color.WHITE);
    graphs.clearRect(0, 0, dimension.width, dimension.height);           
    container.paint(graphs);
    

    the method clearRect is used to actually paint the background with the color you defined.