Search code examples
javaswingjframealways-on-top

Trying to bring swing frame to front before taking a screenshot but getting artifacts


I have a part of my app that takes a screenshot of a certain window but before I do so I want to bring the window to the front. This works fine on my Mac machine but when I tested it on in Windows XP on parallels the screenshot always has a grayed out area where the overlapping window was. It seems the screenshot is always taken while the window I want on top is being transferred to the top. I've tried using both:

     frame.setVisible(true);
            and
     frame.setAlwaysOnTop(true);

Does anyone have a reasonable solution for this issue?


Solution

  • If you are trying to take a screenshot of a window w painted by Java, you can just ask it to paint itself on a

    BufferedImage bi = new BufferedImage(
        w.width, w.height, BufferedImage.TYPE_INT_RGB); 
    Graphics g = bi.getGraphics();
    

    by calling the windows' paint(g) method. You can then save the BufferedImage to a file. If you are grabbing an external window, then I believe Oscar Reyes has given you all the answers.